diff --git a/release-0.6/models/layers.html b/release-0.6/models/layers.html index cc71e784..41c04e6b 100644 --- a/release-0.6/models/layers.html +++ b/release-0.6/models/layers.html @@ -6,31 +6,33 @@ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) ga('create', 'UA-36890222-9', 'auto'); ga('send', 'pageview'); -

Model Reference

Basic Layers

These core layers form the foundation of almost all neural networks.

Flux.ChainType.
Chain(layers...)

Chain multiple layers / functions together, so that they are called in sequence on a given input.

m = Chain(x -> x^2, x -> x+1)
+

Model Reference

Basic Layers

These core layers form the foundation of almost all neural networks.

Flux.ChainType.
Chain(layers...)

Chain multiple layers / functions together, so that they are called in sequence on a given input.

m = Chain(x -> x^2, x -> x+1)
 m(5) == 26
 
 m = Chain(Dense(10, 5), Dense(5, 2))
 x = rand(10)
-m(x) == m[2](m[1](x))

Chain 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.

source
Flux.DenseType.
Dense(in::Integer, out::Integer, σ = identity)

Creates a traditional Dense layer with parameters W and b.

y = σ.(W * x .+ b)

The 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.

julia> d = Dense(5, 2)
+m(x) == m[2](m[1](x))

Chain 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.

source
Flux.DenseType.
Dense(in::Integer, out::Integer, σ = identity)

Creates a traditional Dense layer with parameters W and b.

y = σ.(W * x .+ b)

The 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.

julia> d = Dense(5, 2)
 Dense(5, 2)
 
 julia> d(rand(5))
 Tracked 2-element Array{Float64,1}:
   0.00257447
-  -0.00449443
source
Flux.ConvType.
Conv(size, in=>out)
-Conv(size, in=>out, relu)

Standard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.

Data 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.

Takes the keyword arguments pad, stride and dilation.

source
Flux.MaxPoolType.
MaxPool(k)

Max pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source
Flux.MeanPoolType.
MeanPool(k)

Mean pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source

Recurrent Layers

Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

Flux.RNNFunction.
RNN(in::Integer, out::Integer, σ = tanh)

The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

source
Flux.LSTMFunction.
LSTM(in::Integer, out::Integer)

Long Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.GRUFunction.
GRU(in::Integer, out::Integer)

Gated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.RecurType.
Recur(cell)

Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

h, y = cell(h, x...)

For example, here's a recurrent network that keeps a running total of its inputs.

accum(h, x) = (h+x, x)
+  -0.00449443
source
Flux.ConvType.
Conv(size, in=>out)
+Conv(size, in=>out, relu)

Standard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.

Data 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.

Takes the keyword arguments pad, stride and dilation.

source
Flux.MaxPoolType.
MaxPool(k)

Max pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source
Flux.MeanPoolType.
MeanPool(k)

Mean pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source

Additional Convolution Layers

DepthwiseConv(size, in)
+DepthwiseConv(size, in=>mul)
+DepthwiseConv(size, in=>mul, relu)

Depthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.

Data 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.

Takes the keyword arguments pad and stride.

source

Recurrent Layers

Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

Flux.RNNFunction.
RNN(in::Integer, out::Integer, σ = tanh)

The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

source
Flux.LSTMFunction.
LSTM(in::Integer, out::Integer)

Long Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.GRUFunction.
GRU(in::Integer, out::Integer)

Gated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.RecurType.
Recur(cell)

Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

h, y = cell(h, x...)

For example, here's a recurrent network that keeps a running total of its inputs.

accum(h, x) = (h+x, x)
 rnn = Flux.Recur(accum, 0)
 rnn(2) # 2
 rnn(3) # 3
 rnn.state # 5
 rnn.(1:10) # apply to a sequence
-rnn.state # 60
source

Activation Functions

Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.

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.

NNlib.σFunction.
σ(x) = 1 / (1 + exp(-x))

Classic sigmoid activation function.

NNlib.reluFunction.
relu(x) = max(0, x)

Rectified Linear Unit activation function.

NNlib.leakyreluFunction.
leakyrelu(x) = max(0.01x, x)

Leaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).

NNlib.eluFunction.
elu(x, α = 1) =
+rnn.state # 60
source

Activation Functions

Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.

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.

NNlib.σFunction.
σ(x) = 1 / (1 + exp(-x))

Classic sigmoid activation function.

NNlib.reluFunction.
relu(x) = max(0, x)

Rectified Linear Unit activation function.

NNlib.leakyreluFunction.
leakyrelu(x) = max(0.01x, x)

Leaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).

NNlib.eluFunction.
elu(x, α = 1) =
   x > 0 ? x : α * (exp(x) - 1)

Exponential 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).

NNlib.swishFunction.
swish(x) = x * σ(x)

Self-gated actvation function. See Swish: a Self-Gated Activation Function.

Normalisation & Regularisation

These layers don't affect the structure of the network but may improve training times or reduce overfitting.

Flux.testmode!Function.
testmode!(m)
-testmode!(m, false)

Put layers like Dropout and BatchNorm into testing mode (or back to training mode with false).

source
Flux.BatchNormType.
BatchNorm(channels::Integer, σ = identity;
+testmode!(m, false)

Put layers like Dropout and BatchNorm into testing mode (or back to training mode with false).

source
Flux.BatchNormType.
BatchNorm(channels::Integer, σ = identity;
           initβ = zeros, initγ = ones,
           ϵ = 1e-8, momentum = .1)

Batch Normalization layer. The channels input should be the size of the channel dimension in your data (see below).

Given 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.)

BatchNorm 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).

See Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.

Example:

m = Chain(
   Dense(28^2, 64),
   BatchNorm(64, relu),
   Dense(64, 10),
   BatchNorm(10),
-  softmax)
source
Flux.DropoutType.
Dropout(p)

A Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.

Does nothing to the input once in testmode!.

source
Flux.LayerNormType.
LayerNorm(h::Integer)

A 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.

source
+ softmax)
source
Flux.DropoutType.
Dropout(p)

A Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.

Does nothing to the input once in testmode!.

source
Flux.LayerNormType.
LayerNorm(h::Integer)

A 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.

source
diff --git a/release-0.6/search_index.js b/release-0.6/search_index.js index cc482b06..03a537ea 100644 --- a/release-0.6/search_index.js +++ b/release-0.6/search_index.js @@ -208,6 +208,22 @@ var documenterSearchIndex = {"docs": [ "text": "These core layers form the foundation of almost all neural networks.Chain\nDense\nConv\nMaxPool\nMeanPool" }, +{ + "location": "models/layers.html#Flux.DepthwiseConv", + "page": "Model Reference", + "title": "Flux.DepthwiseConv", + "category": "type", + "text": "DepthwiseConv(size, in)\nDepthwiseConv(size, in=>mul)\nDepthwiseConv(size, in=>mul, relu)\n\nDepthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.\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 and stride.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Additional-Convolution-Layers-1", + "page": "Model Reference", + "title": "Additional Convolution Layers", + "category": "section", + "text": "DepthwiseConv" +}, + { "location": "models/layers.html#Flux.RNN", "page": "Model Reference", @@ -352,38 +368,6 @@ var documenterSearchIndex = {"docs": [ "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.using Flux.Tracker\n\nW = param(rand(2, 5))\nb = param(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\nparams = Params([W, b])\ngrads = Tracker.gradient(() -> loss(x, y), params)We want to update each parameter, using the gradient, in order to improve (reduce) the loss. Here\'s one way to do that:using Flux.Tracker: grad, update!\n\nfunction sgd()\n η = 0.1 # Learning Rate\n for p in (W, b)\n update!(p, -η * grads[p])\n end\nendIf we call sgd, the parameters W and b will change and our loss should go down.There are two pieces here: one is that we need a list of trainable parameters for the model ([W, b] in this case), and the other is the update step. In this case the update is simply gradient descent (x .-= η .* Δ), but we might choose to do something more advanced, like adding momentum.In this case, getting the variables is trivial, but you can imagine it\'d be more of a pain with some complex stack of layers.m = Chain(\n Dense(10, 5, σ),\n Dense(5, 2), softmax)Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.For the update step, there\'s nothing whatsoever wrong with writing the loop above – it\'ll work just fine – but Flux provides various optimisers that make it more convenient.opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1\n\nopt() # Carry out the update, modifying `W` and `b`.An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data." }, -{ - "location": "training/optimisers.html#Flux.Optimise.SGD", - "page": "Optimisers", - "title": "Flux.Optimise.SGD", - "category": "function", - "text": "SGD(params, η = 0.1; decay = 0)\n\nClassic gradient descent optimiser with learning rate η. For each parameter p and its gradient δp, this runs p -= η*δp.\n\nSupports inverse decaying learning rate if the decay argument is provided.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.Momentum", - "page": "Optimisers", - "title": "Flux.Optimise.Momentum", - "category": "function", - "text": "Momentum(params, η = 0.01; ρ = 0.9, decay = 0)\n\nSGD with learning rate η, momentum ρ and optional learning rate inverse decay.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.Nesterov", - "page": "Optimisers", - "title": "Flux.Optimise.Nesterov", - "category": "function", - "text": "Nesterov(params, η = 0.01; ρ = 0.9, decay = 0)\n\nSGD with learning rate η, Nesterov momentum ρ and optional learning rate inverse decay.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.ADAM", - "page": "Optimisers", - "title": "Flux.Optimise.ADAM", - "category": "function", - "text": "ADAM(params, η = 0.001; β1 = 0.9, β2 = 0.999, ϵ = 1e-08, decay = 0)\n\nADAM optimiser.\n\n\n\n\n\n" -}, - { "location": "training/optimisers.html#Optimiser-Reference-1", "page": "Optimisers", diff --git a/release-0.6/training/optimisers.html b/release-0.6/training/optimisers.html index e8cf3e29..c08db2d7 100644 --- a/release-0.6/training/optimisers.html +++ b/release-0.6/training/optimisers.html @@ -29,4 +29,7 @@ end

If we call sgd, the parameters W an Dense(10, 5, σ), Dense(5, 2), softmax)

Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.

For the update step, there's nothing whatsoever wrong with writing the loop above – it'll work just fine – but Flux provides various optimisers that make it more convenient.

opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1
 
-opt() # Carry out the update, modifying `W` and `b`.

An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data.

Optimiser Reference

All optimisers return a function that, when called, will update the parameters passed to it.

Flux.Optimise.SGDFunction.
SGD(params, η = 0.1; decay = 0)

Classic gradient descent optimiser with learning rate η. For each parameter p and its gradient δp, this runs p -= η*δp.

Supports inverse decaying learning rate if the decay argument is provided.

source
Flux.Optimise.MomentumFunction.
Momentum(params, η = 0.01; ρ = 0.9, decay = 0)

SGD with learning rate η, momentum ρ and optional learning rate inverse decay.

source
Flux.Optimise.NesterovFunction.
Nesterov(params, η = 0.01; ρ = 0.9, decay = 0)

SGD with learning rate η, Nesterov momentum ρ and optional learning rate inverse decay.

source
Flux.Optimise.ADAMFunction.
ADAM(params, η = 0.001; β1 = 0.9, β2 = 0.999, ϵ = 1e-08, decay = 0)

ADAM optimiser.

source
+opt() # Carry out the update, modifying `W` and `b`.

An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data.

Optimiser Reference

All optimisers return a function that, when called, will update the parameters passed to it.

SGD
+Momentum
+Nesterov
+ADAM
diff --git a/stable/models/layers.html b/stable/models/layers.html index cc71e784..41c04e6b 100644 --- a/stable/models/layers.html +++ b/stable/models/layers.html @@ -6,31 +6,33 @@ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) ga('create', 'UA-36890222-9', 'auto'); ga('send', 'pageview'); -

Model Reference

Basic Layers

These core layers form the foundation of almost all neural networks.

Flux.ChainType.
Chain(layers...)

Chain multiple layers / functions together, so that they are called in sequence on a given input.

m = Chain(x -> x^2, x -> x+1)
+

Model Reference

Basic Layers

These core layers form the foundation of almost all neural networks.

Flux.ChainType.
Chain(layers...)

Chain multiple layers / functions together, so that they are called in sequence on a given input.

m = Chain(x -> x^2, x -> x+1)
 m(5) == 26
 
 m = Chain(Dense(10, 5), Dense(5, 2))
 x = rand(10)
-m(x) == m[2](m[1](x))

Chain 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.

source
Flux.DenseType.
Dense(in::Integer, out::Integer, σ = identity)

Creates a traditional Dense layer with parameters W and b.

y = σ.(W * x .+ b)

The 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.

julia> d = Dense(5, 2)
+m(x) == m[2](m[1](x))

Chain 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.

source
Flux.DenseType.
Dense(in::Integer, out::Integer, σ = identity)

Creates a traditional Dense layer with parameters W and b.

y = σ.(W * x .+ b)

The 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.

julia> d = Dense(5, 2)
 Dense(5, 2)
 
 julia> d(rand(5))
 Tracked 2-element Array{Float64,1}:
   0.00257447
-  -0.00449443
source
Flux.ConvType.
Conv(size, in=>out)
-Conv(size, in=>out, relu)

Standard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.

Data 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.

Takes the keyword arguments pad, stride and dilation.

source
Flux.MaxPoolType.
MaxPool(k)

Max pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source
Flux.MeanPoolType.
MeanPool(k)

Mean pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source

Recurrent Layers

Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

Flux.RNNFunction.
RNN(in::Integer, out::Integer, σ = tanh)

The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

source
Flux.LSTMFunction.
LSTM(in::Integer, out::Integer)

Long Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.GRUFunction.
GRU(in::Integer, out::Integer)

Gated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.RecurType.
Recur(cell)

Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

h, y = cell(h, x...)

For example, here's a recurrent network that keeps a running total of its inputs.

accum(h, x) = (h+x, x)
+  -0.00449443
source
Flux.ConvType.
Conv(size, in=>out)
+Conv(size, in=>out, relu)

Standard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.

Data 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.

Takes the keyword arguments pad, stride and dilation.

source
Flux.MaxPoolType.
MaxPool(k)

Max pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source
Flux.MeanPoolType.
MeanPool(k)

Mean pooling layer. k stands for the size of the window for each dimension of the input.

Takes the keyword arguments pad and stride.

source

Additional Convolution Layers

DepthwiseConv(size, in)
+DepthwiseConv(size, in=>mul)
+DepthwiseConv(size, in=>mul, relu)

Depthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.

Data 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.

Takes the keyword arguments pad and stride.

source

Recurrent Layers

Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

Flux.RNNFunction.
RNN(in::Integer, out::Integer, σ = tanh)

The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

source
Flux.LSTMFunction.
LSTM(in::Integer, out::Integer)

Long Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.GRUFunction.
GRU(in::Integer, out::Integer)

Gated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

See this article for a good overview of the internals.

source
Flux.RecurType.
Recur(cell)

Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

h, y = cell(h, x...)

For example, here's a recurrent network that keeps a running total of its inputs.

accum(h, x) = (h+x, x)
 rnn = Flux.Recur(accum, 0)
 rnn(2) # 2
 rnn(3) # 3
 rnn.state # 5
 rnn.(1:10) # apply to a sequence
-rnn.state # 60
source

Activation Functions

Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.

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.

NNlib.σFunction.
σ(x) = 1 / (1 + exp(-x))

Classic sigmoid activation function.

NNlib.reluFunction.
relu(x) = max(0, x)

Rectified Linear Unit activation function.

NNlib.leakyreluFunction.
leakyrelu(x) = max(0.01x, x)

Leaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).

NNlib.eluFunction.
elu(x, α = 1) =
+rnn.state # 60
source

Activation Functions

Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.

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.

NNlib.σFunction.
σ(x) = 1 / (1 + exp(-x))

Classic sigmoid activation function.

NNlib.reluFunction.
relu(x) = max(0, x)

Rectified Linear Unit activation function.

NNlib.leakyreluFunction.
leakyrelu(x) = max(0.01x, x)

Leaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).

NNlib.eluFunction.
elu(x, α = 1) =
   x > 0 ? x : α * (exp(x) - 1)

Exponential 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).

NNlib.swishFunction.
swish(x) = x * σ(x)

Self-gated actvation function. See Swish: a Self-Gated Activation Function.

Normalisation & Regularisation

These layers don't affect the structure of the network but may improve training times or reduce overfitting.

Flux.testmode!Function.
testmode!(m)
-testmode!(m, false)

Put layers like Dropout and BatchNorm into testing mode (or back to training mode with false).

source
Flux.BatchNormType.
BatchNorm(channels::Integer, σ = identity;
+testmode!(m, false)

Put layers like Dropout and BatchNorm into testing mode (or back to training mode with false).

source
Flux.BatchNormType.
BatchNorm(channels::Integer, σ = identity;
           initβ = zeros, initγ = ones,
           ϵ = 1e-8, momentum = .1)

Batch Normalization layer. The channels input should be the size of the channel dimension in your data (see below).

Given 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.)

BatchNorm 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).

See Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.

Example:

m = Chain(
   Dense(28^2, 64),
   BatchNorm(64, relu),
   Dense(64, 10),
   BatchNorm(10),
-  softmax)
source
Flux.DropoutType.
Dropout(p)

A Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.

Does nothing to the input once in testmode!.

source
Flux.LayerNormType.
LayerNorm(h::Integer)

A 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.

source
+ softmax)
source
Flux.DropoutType.
Dropout(p)

A Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.

Does nothing to the input once in testmode!.

source
Flux.LayerNormType.
LayerNorm(h::Integer)

A 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.

source
diff --git a/stable/search_index.js b/stable/search_index.js index cc482b06..03a537ea 100644 --- a/stable/search_index.js +++ b/stable/search_index.js @@ -208,6 +208,22 @@ var documenterSearchIndex = {"docs": [ "text": "These core layers form the foundation of almost all neural networks.Chain\nDense\nConv\nMaxPool\nMeanPool" }, +{ + "location": "models/layers.html#Flux.DepthwiseConv", + "page": "Model Reference", + "title": "Flux.DepthwiseConv", + "category": "type", + "text": "DepthwiseConv(size, in)\nDepthwiseConv(size, in=>mul)\nDepthwiseConv(size, in=>mul, relu)\n\nDepthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.\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 and stride.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Additional-Convolution-Layers-1", + "page": "Model Reference", + "title": "Additional Convolution Layers", + "category": "section", + "text": "DepthwiseConv" +}, + { "location": "models/layers.html#Flux.RNN", "page": "Model Reference", @@ -352,38 +368,6 @@ var documenterSearchIndex = {"docs": [ "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.using Flux.Tracker\n\nW = param(rand(2, 5))\nb = param(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\nparams = Params([W, b])\ngrads = Tracker.gradient(() -> loss(x, y), params)We want to update each parameter, using the gradient, in order to improve (reduce) the loss. Here\'s one way to do that:using Flux.Tracker: grad, update!\n\nfunction sgd()\n η = 0.1 # Learning Rate\n for p in (W, b)\n update!(p, -η * grads[p])\n end\nendIf we call sgd, the parameters W and b will change and our loss should go down.There are two pieces here: one is that we need a list of trainable parameters for the model ([W, b] in this case), and the other is the update step. In this case the update is simply gradient descent (x .-= η .* Δ), but we might choose to do something more advanced, like adding momentum.In this case, getting the variables is trivial, but you can imagine it\'d be more of a pain with some complex stack of layers.m = Chain(\n Dense(10, 5, σ),\n Dense(5, 2), softmax)Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.For the update step, there\'s nothing whatsoever wrong with writing the loop above – it\'ll work just fine – but Flux provides various optimisers that make it more convenient.opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1\n\nopt() # Carry out the update, modifying `W` and `b`.An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data." }, -{ - "location": "training/optimisers.html#Flux.Optimise.SGD", - "page": "Optimisers", - "title": "Flux.Optimise.SGD", - "category": "function", - "text": "SGD(params, η = 0.1; decay = 0)\n\nClassic gradient descent optimiser with learning rate η. For each parameter p and its gradient δp, this runs p -= η*δp.\n\nSupports inverse decaying learning rate if the decay argument is provided.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.Momentum", - "page": "Optimisers", - "title": "Flux.Optimise.Momentum", - "category": "function", - "text": "Momentum(params, η = 0.01; ρ = 0.9, decay = 0)\n\nSGD with learning rate η, momentum ρ and optional learning rate inverse decay.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.Nesterov", - "page": "Optimisers", - "title": "Flux.Optimise.Nesterov", - "category": "function", - "text": "Nesterov(params, η = 0.01; ρ = 0.9, decay = 0)\n\nSGD with learning rate η, Nesterov momentum ρ and optional learning rate inverse decay.\n\n\n\n\n\n" -}, - -{ - "location": "training/optimisers.html#Flux.Optimise.ADAM", - "page": "Optimisers", - "title": "Flux.Optimise.ADAM", - "category": "function", - "text": "ADAM(params, η = 0.001; β1 = 0.9, β2 = 0.999, ϵ = 1e-08, decay = 0)\n\nADAM optimiser.\n\n\n\n\n\n" -}, - { "location": "training/optimisers.html#Optimiser-Reference-1", "page": "Optimisers", diff --git a/stable/training/optimisers.html b/stable/training/optimisers.html index e8cf3e29..c08db2d7 100644 --- a/stable/training/optimisers.html +++ b/stable/training/optimisers.html @@ -29,4 +29,7 @@ end

If we call sgd, the parameters W an Dense(10, 5, σ), Dense(5, 2), softmax)

Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.

For the update step, there's nothing whatsoever wrong with writing the loop above – it'll work just fine – but Flux provides various optimisers that make it more convenient.

opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1
 
-opt() # Carry out the update, modifying `W` and `b`.

An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data.

Optimiser Reference

All optimisers return a function that, when called, will update the parameters passed to it.

Flux.Optimise.SGDFunction.
SGD(params, η = 0.1; decay = 0)

Classic gradient descent optimiser with learning rate η. For each parameter p and its gradient δp, this runs p -= η*δp.

Supports inverse decaying learning rate if the decay argument is provided.

source
Flux.Optimise.MomentumFunction.
Momentum(params, η = 0.01; ρ = 0.9, decay = 0)

SGD with learning rate η, momentum ρ and optional learning rate inverse decay.

source
Flux.Optimise.NesterovFunction.
Nesterov(params, η = 0.01; ρ = 0.9, decay = 0)

SGD with learning rate η, Nesterov momentum ρ and optional learning rate inverse decay.

source
Flux.Optimise.ADAMFunction.
ADAM(params, η = 0.001; β1 = 0.9, β2 = 0.999, ϵ = 1e-08, decay = 0)

ADAM optimiser.

source
+opt() # Carry out the update, modifying `W` and `b`.

An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data.

Optimiser Reference

All optimisers return a function that, when called, will update the parameters passed to it.

SGD
+Momentum
+Nesterov
+ADAM
diff --git a/v0.6.9/assets/arrow.svg b/v0.6.9/assets/arrow.svg new file mode 100644 index 00000000..ee2798d3 --- /dev/null +++ b/v0.6.9/assets/arrow.svg @@ -0,0 +1,63 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + diff --git a/v0.6.9/assets/documenter.css b/v0.6.9/assets/documenter.css new file mode 100644 index 00000000..26c8166f --- /dev/null +++ b/v0.6.9/assets/documenter.css @@ -0,0 +1,573 @@ +/* + * The default CSS style for Documenter.jl generated sites + * + * Heavily inspired by the Julia Sphinx theme + * https://github.com/JuliaLang/JuliaDoc + * which extends the sphinx_rtd_theme + * https://github.com/snide/sphinx_rtd_theme + * + * Part of Documenter.jl + * https://github.com/JuliaDocs/Documenter.jl + * + * License: MIT + */ + +/* fonts */ +body, input { + font-family: 'Lato', 'Helvetica Neue', Arial, sans-serif; + font-size: 16px; + color: #222; + text-rendering: optimizeLegibility; +} + +pre, code, kbd { + font-family: 'Roboto Mono', Monaco, courier, monospace; + font-size: 0.90em; +} + +pre code { + font-size: 1em; +} + +a { + color: #2980b9; + text-decoration: none; +} + +a:hover { + color: #3091d1; +} + +a:visited { + color: #9b59b6; +} + +body { + line-height: 1.5; +} + +h1 { + font-size: 1.75em; +} + +/* Unless the

the is very first thing on the page (i.e. the second element + * in the
, * after the
, we add some additional styling to it + * to make it stand out a bit more. This way we get a reasonable fallback if CSS3 + * selectors are not supported in the browser. + */ +article > h1:not(:nth-child(2)) { + margin: 2.5em 0 0; + padding-bottom: 0.30em; + border-bottom: 1px solid #e5e5e5; +} +h2 { + font-size: 1.50em; + margin: 2.3em 0 0; + padding-bottom: 0.25em; + border-bottom: 1px solid #e5e5e5; +} +h3 { + font-size: 1.25em; + margin: 2.0em 0 0; +} +h4 { font-size: 1.15em; } +h5 { font-size: 1.10em; } +h6 { font-size: 1em; } + +h4, h5, h6 { + margin-top: 1.5em; + margin-bottom: 1em; +} + +img { + max-width: 100%; +} + +table { + border-collapse: collapse; + margin: 1em 0; +} + +th, td { + border: 1px solid #e1e4e5; + padding: 0.5em 1em; +} + +th { + border-bottom-width: 2px; +} + +tr:nth-child(even) { + background-color: #f3f6f6; +} + +hr { + border: 0; + border-top: 1px solid #e5e5e5; +} + +/* Inline code and code blocks */ + +code { + padding: 0.1em; + background-color: rgba(0,0,0,.04); + border-radius: 3px; +} + +pre { + background-color: #f5f5f5; + border: 1px solid #dddddd; + border-radius: 3px; + padding: 0.5em; + overflow: auto; +} + +pre code { + padding: 0; + background-color: initial; +} + +kbd { + font-size: 0.70em; + display: inline-block; + padding: 0.1em 0.5em 0.4em 0.5em; + line-height: 1.0em; + color: #444d56; + vertical-align: middle; + background-color: #fafbfc; + border: solid 1px #c6cbd1; + border-bottom-color: #959da5; + border-radius: 3px; + box-shadow: inset 0 -1px 0 #959da5; +} + +/* Headers in admonitions and docstrings */ +.admonition h1, +article section.docstring h1 { + font-size: 1.25em; +} + +.admonition h2, +article section.docstring h2 { + font-size: 1.10em; +} + +.admonition h3, +.admonition h4, +.admonition h5, +.admonition h6, +article section.docstring h3, +article section.docstring h4, +article section.docstring h5, +article section.docstring h6 { + font-size: 1em; +} + +/* Navigation */ +nav.toc { + position: fixed; + top: 0; + left: 0; + bottom: 0; + width: 20em; + overflow-y: auto; + padding: 1em 0; + background-color: #fcfcfc; + box-shadow: inset -14px 0px 5px -12px rgb(210,210,210); +} + +nav.toc .logo { + margin: 0 auto; + display: block; + max-height: 6em; + max-width: 18em; +} + +nav.toc h1 { + text-align: center; + margin-top: .57em; + margin-bottom: 0; +} + +nav.toc select { + display: block; + height: 2em; + padding: 0 1.6em 0 1em; + min-width: 7em; + max-width: 90%; + max-width: calc(100% - 5em); + margin: 0 auto; + font-size: .83em; + border: 1px solid #c9c9c9; + border-radius: 1em; + + /* TODO: doesn't seem to be centered on Safari */ + text-align: center; + text-align-last: center; + + appearance: none; + -moz-appearance: none; + -webkit-appearance: none; + + background: white url("arrow.svg"); + background-size: 1.155em; + background-repeat: no-repeat; + background-position: right; +} + +nav.toc select:hover { + border: 1px solid #a0a0a0; +} + +nav.toc select option { + text-align: center; +} + +nav.toc input { + display: block; + height: 2em; + width: 90%; + width: calc(100% - 5em); + margin: 1.2em auto; + padding: 0 1em; + border: 1px solid #c9c9c9; + border-radius: 1em; + font-size: .83em; +} + +nav.toc > ul * { + margin: 0; +} + +nav.toc ul { + color: #404040; + padding: 0; + list-style: none; +} + +nav.toc ul .toctext { + color: inherit; + display: block; +} + +nav.toc ul a:hover { + color: #fcfcfc; + background-color: #4e4a4a; +} + +nav.toc ul.internal a { + color: inherit; + display: block; +} + +nav.toc ul.internal a:hover { + background-color: #d6d6d6; +} + +nav.toc ul.internal { + background-color: #e3e3e3; + box-shadow: inset -14px 0px 5px -12px rgb(210,210,210); + list-style: none; +} + +nav.toc ul.internal li.toplevel { + border-top: 1px solid #909090; + font-weight: bold; +} + +nav.toc ul.internal li.toplevel:first-child { + border-top: none; +} + +nav.toc .toctext { + padding-top: 0.3em; + padding-bottom: 0.3em; + padding-right: 1em; +} + +nav.toc ul .toctext { + padding-left: 1em; +} + +nav.toc ul ul .toctext { + padding-left: 2em; +} + +nav.toc ul ul ul .toctext { + padding-left: 3em; +} + +nav.toc li.current > .toctext { + border-top: 1px solid #c9c9c9; + border-bottom: 1px solid #c9c9c9; + color: #404040; + font-weight: bold; + background-color: white; +} + +article { + margin-left: 20em; + min-width: 20em; + max-width: 48em; + padding: 2em; +} + +article > header {} + +article > header div#topbar { + display: none; +} + +article > header nav ul { + display: inline-block; + list-style: none; + margin: 0; + padding: 0; +} + +article > header nav li { + display: inline-block; + padding-right: 0.2em; +} + +article > header nav li:before { + content: "»"; + padding-right: 0.2em; +} + +article > header .edit-page { + float: right; +} + +article > footer {} + +article > footer a.prev { + float: left; +} +article > footer a.next { + float: right; +} + +article > footer a .direction:after { + content: ": "; +} + +article hr { + margin: 1em 0; +} + +article section.docstring { + border: 1px solid #ddd; + margin: 0.5em 0; + padding: 0.5em; + border-radius: 3px; +} + +article section.docstring .docstring-header { + margin-bottom: 1em; +} + +article section.docstring .docstring-binding { + color: #333; + font-weight: bold; +} + +article section.docstring .docstring-category { + font-style: italic; +} + +article section.docstring a.source-link { + display: block; + font-weight: bold; +} + +.nav-anchor, +.nav-anchor:hover, +.nav-anchor:visited { + color: #333; +} + +/* + * Admonitions + * + * Colors (title, body) + * warning: #f0b37e #ffedcc (orange) + * note: #6ab0de #e7f2fa (blue) + * tip: #1abc9c #dbfaf4 (green) +*/ +.admonition { + border-radius: 3px; + background-color: #eeeeee; +} + +.admonition-title { + border-radius: 3px 3px 0 0; + background-color: #9b9b9b; + padding: 0.15em 0.5em; +} + +.admonition-text { + padding: 0.5em; +} + +.admonition-text > :first-child { + margin-top: 0; +} + +.admonition-text > :last-child { + margin-bottom: 0; +} + +.admonition > .admonition-title:before { + font-family: "FontAwesome"; + margin-right: 5px; + content: "\f06a"; +} + +.admonition.warning > .admonition-title { + background-color: #f0b37e; +} + +.admonition.warning { + background-color: #ffedcc; +} + +.admonition.note > .admonition-title { + background-color: #6ab0de; +} + +.admonition.note { + background-color: #e7f2fa; +} + +.admonition.tip > .admonition-title { + background-color: #1abc9c; +} + +.admonition.tip { + background-color: #dbfaf4; +} + + +/* footnotes */ +.footnote { + padding-left: 0.8em; + border-left: 2px solid #ccc; +} + +/* Search page */ +#search-results .category { + font-size: smaller; +} + +/* Overriding the block style of highligh.js. + * We have to override the padding and the background-color, since we style this + * part ourselves. Specifically, we style the
 surrounding the , while
+ * highlight.js applies the .hljs style directly to the  tag.
+ */
+.hljs {
+    background-color: transparent;
+    padding: 0;
+}
+
+@media only screen and (max-width: 768px) {
+    nav.toc {
+        position: fixed;
+        overflow-y: scroll;
+        width: 16em;
+        left: -16em;
+        -webkit-overflow-scrolling: touch;
+        -webkit-transition-property: left; /* Safari */
+        -webkit-transition-duration: 0.3s; /* Safari */
+        transition-property: left;
+        transition-duration: 0.3s;
+        -webkit-transition-timing-function: ease-out; /* Safari */
+        transition-timing-function: ease-out;
+        z-index: 2;
+    }
+
+    nav.toc.show {
+        left: 0;
+    }
+
+    article {
+        margin-left: 0;
+        padding: 3em 0.9em 0 0.9em; /* top right bottom left */
+        overflow-wrap: break-word;
+    }
+
+    article > header {
+        position: fixed;
+        left: 0;
+        z-index: 1;
+    }
+
+    article > header nav, hr {
+        display: none;
+    }
+
+    article > header div#topbar {
+        display: block; /* is mobile */
+        position: fixed;
+        width: 100%;
+        height: 1.5em;
+        padding-top: 1em;
+        padding-bottom: 1em;
+        background-color: #fcfcfc;
+        box-shadow: 0 1px 3px rgba(0,0,0,.26);
+        top: 0;
+        -webkit-transition-property: top; /* Safari */
+        -webkit-transition-duration: 0.3s; /* Safari */
+        transition-property: top;
+        transition-duration: 0.3s;
+    }
+
+    article > header div#topbar.headroom--unpinned.headroom--not-top.headroom--not-bottom {
+        top: -4em;
+        -webkit-transition-property: top; /* Safari */
+        -webkit-transition-duration: 0.7s; /* Safari */
+        transition-property: top;
+        transition-duration: 0.7s;
+    }
+
+    article > header div#topbar span {
+        position: fixed;
+        width: 80%;
+        height: 1.5em;
+        margin-top: -0.1em;
+        margin-left: 0.9em;
+        font-size: 1.2em;
+        overflow: hidden;
+    }
+
+    article > header div#topbar a.fa-bars {
+        float: right;
+        padding: 0.6em;
+        margin-top: -0.6em;
+        margin-right: 0.3em;
+        font-size: 1.5em;
+    }
+
+    article > header div#topbar a.fa-bars:visited {
+        color: #3091d1;
+    }
+
+    article table {
+        overflow-x: auto;
+        display: block;
+    }
+
+    article div.MathJax_Display {
+        overflow: scroll;
+    }
+
+    article span.MathJax {
+        overflow: hidden;
+    }
+}
+
+@media only screen and (max-width: 320px) {
+    body {
+        font-size: 15px;
+    }
+}
diff --git a/v0.6.9/assets/documenter.js b/v0.6.9/assets/documenter.js
new file mode 100644
index 00000000..5d31622f
--- /dev/null
+++ b/v0.6.9/assets/documenter.js
@@ -0,0 +1,129 @@
+/*
+ * Part of Documenter.jl
+ *     https://github.com/JuliaDocs/Documenter.jl
+ *
+ * License: MIT
+ */
+
+requirejs.config({
+    paths: {
+        'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min',
+        'jqueryui': 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min',
+        'headroom': 'https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.3/headroom.min',
+        'mathjax': 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_HTML',
+        'highlight': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min',
+        'highlight-julia': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/julia.min',
+        'highlight-julia-repl': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/julia-repl.min',
+    },
+    shim: {
+        'mathjax' : {
+            exports: "MathJax"
+        },
+        'highlight-julia': ['highlight'],
+        'highlight-julia-repl': ['highlight'],
+    }
+});
+
+// Load MathJax
+require(['mathjax'], function(MathJax) {
+    MathJax.Hub.Config({
+      "tex2jax": {
+        inlineMath: [['$','$'], ['\\(','\\)']],
+        processEscapes: true
+      }
+    });
+    MathJax.Hub.Config({
+      config: ["MMLorHTML.js"],
+      jax: [
+        "input/TeX",
+        "output/HTML-CSS",
+        "output/NativeMML"
+      ],
+      extensions: [
+        "MathMenu.js",
+        "MathZoom.js",
+        "TeX/AMSmath.js",
+        "TeX/AMSsymbols.js",
+        "TeX/autobold.js",
+        "TeX/autoload-all.js"
+      ]
+    });
+    MathJax.Hub.Config({
+      TeX: { equationNumbers: { autoNumber: "AMS" } }
+    });
+})
+
+require(['jquery', 'highlight', 'highlight-julia', 'highlight-julia-repl'], function($, hljs) {
+    $(document).ready(function() {
+        hljs.initHighlighting();
+    })
+
+})
+
+// update the version selector with info from the siteinfo.js and ../versions.js files
+require(['jquery'], function($) {
+    $(document).ready(function() {
+        var version_selector = $("#version-selector");
+
+        // add the current version to the selector based on siteinfo.js, but only if the selector is empty
+        if (typeof DOCUMENTER_CURRENT_VERSION !== 'undefined' && $('#version-selector > option').length == 0) {
+            var option = $("");
+            version_selector.append(option);
+        }
+
+        if (typeof DOC_VERSIONS !== 'undefined') {
+            var existing_versions = $('#version-selector > option');
+            var existing_versions_texts = existing_versions.map(function(i,x){return x.text});
+            DOC_VERSIONS.forEach(function(each) {
+                var version_url = documenterBaseURL + "/../" + each;
+                var existing_id = $.inArray(each, existing_versions_texts);
+                // if not already in the version selector, add it as a new option,
+                // otherwise update the old option with the URL and enable it
+                if (existing_id == -1) {
+                    var option = $("");
+                    version_selector.append(option);
+                } else {
+                    var option = existing_versions[existing_id];
+                    option.value = version_url;
+                    option.disabled = false;
+                }
+            });
+        }
+
+        // only show the version selector if the selector has been populated
+        if ($('#version-selector > option').length > 0) {
+            version_selector.css("visibility", "visible");
+        }
+    })
+
+})
+
+// mobile
+require(['jquery', 'headroom'], function($, Headroom) {
+    $(document).ready(function() {
+        var navtoc = $("nav.toc");
+        $("nav.toc li.current a.toctext").click(function() {
+            navtoc.toggleClass('show');
+        });
+        $("article > header div#topbar a.fa-bars").click(function(ev) {
+            ev.preventDefault();
+            navtoc.toggleClass('show');
+            if (navtoc.hasClass('show')) {
+                var title = $("article > header div#topbar span").text();
+                $("nav.toc ul li a:contains('" + title + "')").focus();
+            }
+        });
+        $("article#docs").bind('click', function(ev) {
+            if ($(ev.target).is('div#topbar a.fa-bars')) {
+                return;
+            }
+            if (navtoc.hasClass('show')) {
+                navtoc.removeClass('show');
+            }
+        });
+        if ($("article > header div#topbar").css('display') == 'block') {
+            var headroom = new Headroom(document.querySelector("article > header div#topbar"), {"tolerance": {"up": 10, "down": 10}});
+            headroom.init();
+        }
+    })
+})
diff --git a/v0.6.9/assets/search.js b/v0.6.9/assets/search.js
new file mode 100644
index 00000000..f99b3786
--- /dev/null
+++ b/v0.6.9/assets/search.js
@@ -0,0 +1,250 @@
+/*
+ * Part of Documenter.jl
+ *     https://github.com/JuliaDocs/Documenter.jl
+ *
+ * License: MIT
+ */
+
+// parseUri 1.2.2
+// (c) Steven Levithan 
+// MIT License
+function parseUri (str) {
+	var	o   = parseUri.options,
+		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
+		uri = {},
+		i   = 14;
+
+	while (i--) uri[o.key[i]] = m[i] || "";
+
+	uri[o.q.name] = {};
+	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
+		if ($1) uri[o.q.name][$1] = $2;
+	});
+
+	return uri;
+};
+parseUri.options = {
+	strictMode: false,
+	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
+	q:   {
+		name:   "queryKey",
+		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
+	},
+	parser: {
+		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
+		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
+	}
+};
+
+requirejs.config({
+    paths: {
+        'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min',
+        'lunr': 'https://cdnjs.cloudflare.com/ajax/libs/lunr.js/2.3.1/lunr.min',
+        'lodash': 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min',
+    }
+});
+
+var currentScript = document.currentScript;
+
+require(["jquery", "lunr", "lodash"], function($, lunr, _) {
+    $("#search-form").submit(function(e) {
+        e.preventDefault()
+    })
+
+    // list below is the lunr 2.1.3 list minus the intersect with names(Base)
+    // (all, any, get, in, is, which) and (do, else, for, let, where, while, with)
+    // ideally we'd just filter the original list but it's not available as a variable
+    lunr.stopWordFilter = lunr.generateStopWordFilter([
+        'a',
+        'able',
+        'about',
+        'across',
+        'after',
+        'almost',
+        'also',
+        'am',
+        'among',
+        'an',
+        'and',
+        'are',
+        'as',
+        'at',
+        'be',
+        'because',
+        'been',
+        'but',
+        'by',
+        'can',
+        'cannot',
+        'could',
+        'dear',
+        'did',
+        'does',
+        'either',
+        'ever',
+        'every',
+        'from',
+        'got',
+        'had',
+        'has',
+        'have',
+        'he',
+        'her',
+        'hers',
+        'him',
+        'his',
+        'how',
+        'however',
+        'i',
+        'if',
+        'into',
+        'it',
+        'its',
+        'just',
+        'least',
+        'like',
+        'likely',
+        'may',
+        'me',
+        'might',
+        'most',
+        'must',
+        'my',
+        'neither',
+        'no',
+        'nor',
+        'not',
+        'of',
+        'off',
+        'often',
+        'on',
+        'only',
+        'or',
+        'other',
+        'our',
+        'own',
+        'rather',
+        'said',
+        'say',
+        'says',
+        'she',
+        'should',
+        'since',
+        'so',
+        'some',
+        'than',
+        'that',
+        'the',
+        'their',
+        'them',
+        'then',
+        'there',
+        'these',
+        'they',
+        'this',
+        'tis',
+        'to',
+        'too',
+        'twas',
+        'us',
+        'wants',
+        'was',
+        'we',
+        'were',
+        'what',
+        'when',
+        'who',
+        'whom',
+        'why',
+        'will',
+        'would',
+        'yet',
+        'you',
+        'your'
+        ])
+
+    // add . as a separator, because otherwise "title": "Documenter.Anchors.add!"
+    // would not find anything if searching for "add!", only for the entire qualification
+    lunr.tokenizer.separator = /[\s\-\.]+/
+
+    // custom trimmer that doesn't strip @ and !, which are used in julia macro and function names
+    lunr.trimmer = function (token) {
+        return token.update(function (s) {
+            return s.replace(/^[^a-zA-Z0-9@!]+/, '').replace(/[^a-zA-Z0-9@!]+$/, '')
+        })
+    }
+
+    lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'juliaStopWordFilter')
+    lunr.Pipeline.registerFunction(lunr.trimmer, 'juliaTrimmer')
+
+    var index = lunr(function () {
+        this.ref('location')
+        this.field('title')
+        this.field('text')
+        documenterSearchIndex['docs'].forEach(function(e) {
+            this.add(e)
+        }, this)
+    })
+    var store = {}
+
+    documenterSearchIndex['docs'].forEach(function(e) {
+        store[e.location] = {title: e.title, category: e.category}
+    })
+
+    $(function(){
+        function update_search(querystring) {
+            tokens = lunr.tokenizer(querystring)
+            results = index.query(function (q) {
+                tokens.forEach(function (t) {
+                    q.term(t.toString(), {
+                        fields: ["title"],
+                        boost: 100,
+                        usePipeline: false,
+                        editDistance: 0,
+                        wildcard: lunr.Query.wildcard.NONE
+                    })
+                    q.term(t.toString(), {
+                        fields: ["title"],
+                        boost: 10,
+                        usePipeline: false,
+                        editDistance: 2,
+                        wildcard: lunr.Query.wildcard.NONE
+                    })
+                    q.term(t.toString(), {
+                        fields: ["text"],
+                        boost: 1,
+                        usePipeline: true,
+                        editDistance: 0,
+                        wildcard: lunr.Query.wildcard.NONE
+                    })
+                })
+            })
+            $('#search-info').text("Number of results: " + results.length)
+            $('#search-results').empty()
+            results.forEach(function(result) {
+                data = store[result.ref]
+                link = $('')
+                link.text(data.title)
+                link.attr('href', documenterBaseURL+'/'+result.ref)
+                cat = $('('+data.category+')')
+                li = $('
  • ').append(link).append(" ").append(cat) + $('#search-results').append(li) + }) + } + + function update_search_box() { + querystring = $('#search-query').val() + update_search(querystring) + } + + $('#search-query').keyup(_.debounce(update_search_box, 250)) + $('#search-query').change(update_search_box) + + search_query_uri = parseUri(window.location).queryKey["q"] + if(search_query_uri !== undefined) { + search_query = decodeURIComponent(search_query_uri.replace(/\+/g, '%20')) + $("#search-query").val(search_query) + } + update_search_box(); + }) +}) diff --git a/v0.6.9/community.html b/v0.6.9/community.html new file mode 100644 index 00000000..3eb998c3 --- /dev/null +++ b/v0.6.9/community.html @@ -0,0 +1,9 @@ + +Community · Flux diff --git a/v0.6.9/data/onehot.html b/v0.6.9/data/onehot.html new file mode 100644 index 00000000..f41342ce --- /dev/null +++ b/v0.6.9/data/onehot.html @@ -0,0 +1,40 @@ + +One-Hot Encoding · Flux

    One-Hot Encoding

    One-Hot Encoding

    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.

    julia> using Flux: onehot, onecold
    +
    +julia> onehot(:b, [:a, :b, :c])
    +3-element Flux.OneHotVector:
    + false
    +  true
    + false
    +
    +julia> onehot(:c, [:a, :b, :c])
    +3-element Flux.OneHotVector:
    + false
    + false
    +  true

    The inverse is onecold (which can take a general probability distribution, as well as just booleans).

    julia> onecold(ans, [:a, :b, :c])
    +:c
    +
    +julia> onecold([true, false, false], [:a, :b, :c])
    +:a
    +
    +julia> onecold([0.3, 0.2, 0.5], [:a, :b, :c])
    +:c

    Batches

    onehotbatch creates a batch (matrix) of one-hot vectors, and onecold treats matrices as batches.

    julia> using Flux: onehotbatch
    +
    +julia> onehotbatch([:b, :a, :b], [:a, :b, :c])
    +3×3 Flux.OneHotMatrix:
    + false   true  false
    +  true  false   true
    + false  false  false
    +
    +julia> onecold(ans, [:a, :b, :c])
    +3-element Array{Symbol,1}:
    +  :b
    +  :a
    +  :b

    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.

    diff --git a/v0.6.9/gpu.html b/v0.6.9/gpu.html new file mode 100644 index 00000000..4cb10004 --- /dev/null +++ b/v0.6.9/gpu.html @@ -0,0 +1,50 @@ + +GPU Support · Flux

    GPU Support

    GPU Support

    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.

    For example, we can use CuArrays (with the cu converter) to run our basic example on an NVIDIA GPU.

    (Note that you need to build Julia 0.6 from source and have CUDA available to use CuArrays – please see the CUDAnative.jl instructions for more details.)

    using CuArrays
    +
    +W = cu(rand(2, 5)) # a 2×5 CuArray
    +b = cu(rand(2))
    +
    +predict(x) = W*x .+ b
    +loss(x, y) = sum((predict(x) .- y).^2)
    +
    +x, y = cu(rand(5)), cu(rand(2)) # Dummy data
    +loss(x, y) # ~ 3

    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.

    If you define a structured model, like a Dense layer or Chain, you just need to convert the internal parameters. Flux provides mapleaves, which allows you to alter all parameters of a model at once.

    d = Dense(10, 5, σ)
    +d = mapleaves(cu, d)
    +d.W # Tracked CuArray
    +d(cu(rand(10))) # CuArray output
    +
    +m = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)
    +m = mapleaves(cu, m)
    +d(cu(rand(10)))

    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.

    julia> using Flux, CuArrays
    +
    +julia> m = Dense(10,5) |> gpu
    +Dense(10, 5)
    +
    +julia> x = rand(10) |> gpu
    +10-element CuArray{Float32,1}:
    + 0.800225
    + ⋮
    + 0.511655
    +
    +julia> m(x)
    +Tracked 5-element CuArray{Float32,1}:
    + -0.30535
    + ⋮
    + -0.618002

    The analogue cpu is also available for moving models and data back off of the GPU.

    julia> x = rand(10) |> gpu
    +10-element CuArray{Float32,1}:
    + 0.235164
    + ⋮
    + 0.192538
    +
    +julia> x |> cpu
    +10-element Array{Float32,1}:
    + 0.235164
    + ⋮
    + 0.192538
    diff --git a/v0.6.9/index.html b/v0.6.9/index.html new file mode 100644 index 00000000..5cf0d599 --- /dev/null +++ b/v0.6.9/index.html @@ -0,0 +1,9 @@ + +Home · Flux

    Home

    Flux: The Julia Machine Learning Library

    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:

    • 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.
    • You 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.
    • Play 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.

    Installation

    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.

    If you have CUDA you can also run ] add CuArrays to get GPU support; see here for more details.

    Learning Flux

    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.

    diff --git a/v0.6.9/internals/tracker.html b/v0.6.9/internals/tracker.html new file mode 100644 index 00000000..1fed9856 --- /dev/null +++ b/v0.6.9/internals/tracker.html @@ -0,0 +1,66 @@ + +Backpropagation · Flux

    Backpropagation

    Flux.Tracker

    Backpropagation, or reverse-mode automatic differentiation, is handled by the Flux.Tracker module.

    julia> using Flux.Tracker

    Here we discuss some more advanced uses of this module, as well as covering its internals.

    Taking Gradients

    In the basics section we covered basic usage of the gradient function.

    using Flux.Tracker
    +
    +Tracker.gradient((a, b) -> a*b, 2, 3) # (3.0 (tracked), 2.0 (tracked))

    gradient is actually just a thin wrapper around the backpropagator-based interface, forward.

    using Flux.Tracker: forward
    +
    +y, back = forward((a, b) -> a*b, 2, 3) # (6.0 (tracked), Flux.Tracker.#9)
    +
    +back(1) # (3.0 (tracked), 2.0 (tracked))

    The forward function returns two results. The first, y, is the original value of the function (perhaps with tracking applied). The second, back, is a new function which, given a sensitivity, returns the sensitivity of the inputs to forward (we call this a "backpropagator"). One use of this interface is to provide custom sensitivities when outputs are not scalar.

    julia> y, back = forward((a, b) -> a.*b, [1,2,3],[4,5,6])
    +(param([4.0, 10.0, 18.0]), Flux.Tracker.#9)
    +
    +julia> back([1,1,1])
    +(param([4.0, 5.0, 6.0]), param([1.0, 2.0, 3.0]))

    We can also take gradients in-place. This can be useful if you only care about first-order gradients.

    a, b = param(2), param(3)
    +
    +c = a*b # 6.0 (tracked)
    +
    +Tracker.back!(c)
    +
    +Tracker.grad(a), Tracker.grad(b) # (3.0, 2.0)

    Tracked Arrays

    The param function converts a normal Julia array into a new object that, while behaving like an array, tracks extra information that allows us to calculate derivatives. For example, say we multiply two parameters:

    julia> W = param([1 2; 3 4])
    +Tracked 2×2 Array{Float64,2}:
    + 1.0  2.0
    + 3.0  4.0
    +
    +julia> x = param([5, 6])
    +Tracked 2-element Array{Float64,1}:
    + 5.0
    + 6.0
    +
    +julia> y = W*x
    +Tracked 2-element Array{Float64,1}:
    + 17.0
    + 39.0

    The output y is also a TrackedArray object. We can now backpropagate sensitivities to W and x via the back! function, and see the gradients accumulated in the W and x tracked arrays:

    julia> Tracker.back!(y, [1, -1])
    +
    +julia> W.grad
    +2×2 Array{Float64,2}:
    + 5.0   6.0
    +-5.0  -6.0
    +
    +julia> x.grad
    +2-element Array{Float64,1}:
    + -2.0
    + -2.0

    You may sometimes want to drop derivative information and just get the plain value back. You can do this by calling Tracker.data(W).

    Custom Gradients

    We can hook in to the processes above to implement custom gradients for a function or kernel. For a toy example, imagine a custom implementation of minus:

    minus(a, b) = a - b

    Firstly, we must tell the tracker system to stop when it sees a call to minus, and record it. We can do this using dispatch:

    using Flux.Tracker: TrackedArray, track, @grad
    +
    +minus(a::TrackedArray, b::TrackedArray) = track(minus, a, b)

    track takes care of building a new Tracked object and recording the operation on the tape. We just need to provide a gradient definition.

    @grad function minus(a, b)
    +  return minus(data(a), data(b)), Δ -> (Δ, -Δ)
    +end

    This is essentially just a way of overloading the forward function we saw above. We strip tracking from a and b so that we are calling the original definition of minus (otherwise, we'd just try to track the call again and hit an infinite regress).

    Note that in the backpropagator we don't call data(a); we do in fact want to track this, since nest AD will take a derivative through the backpropagator itself. For example, the gradient of * might look like this.

    @grad a * b = data(a)*data(b), Δ -> (Δ*b, a*Δ)

    We can then calculate the first derivative of minus as follows:

    a = param([1,2,3])
    +b = param([3,2,1])
    +
    +c = minus(a, b)  # [-2.0 (tracked), 0.0 (tracked), 2.0 (tracked)]
    +
    +Tracker.back!(c, 1)
    +Tracker.grad(a)  # [1.00, 1.00, 1.00]
    +Tracker.grad(b)  # [-1.00, -1.00, -1.00]

    For multi-argument functions with custom gradients, you likely want to catch not just minus(::TrackedArray, ::TrackedArray) but also minus(::Array, TrackedArray) and so on. To do so, just define those extra signatures as needed:

    minus(a::AbstractArray, b::TrackedArray) = Tracker.track(minus, a, b)
    +minus(a::TrackedArray, b::AbstractArray) = Tracker.track(minus, a, b)

    Tracked Internals

    All Tracked* objects (TrackedArray, TrackedReal) are light wrappers around the Tracked type, which you can access via the .tracker field.

    julia> x.tracker
    +Flux.Tracker.Tracked{Array{Float64,1}}(0x00000000, Flux.Tracker.Call{Nothing,Tuple{}}(nothing, ()), true, [5.0, 6.0], [-2.0, -2.0])

    The Tracker stores the gradient of a given object, which we've seen before.

    julia> x.tracker.grad
    +2-element Array{Float64,1}:
    + -2.0
    + -2.0

    The tracker also contains a Call object, which simply represents a function call that was made at some point during the forward pass. For example, the + call would look like this:

    julia> Tracker.Call(+, 1, 2)
    +Flux.Tracker.Call{Base.#+,Tuple{Int64,Int64}}(+, (1, 2))

    In the case of the y we produced above, we can see that it stores the call that produced it – that is, W*x.

    julia> y.tracker.f
    +Flux.Tracker.Call{...}(*, (param([1.0 2.0; 3.0 4.0]), param([5.0, 6.0])))

    Notice that because the arguments to the call may also be tracked arrays, storing their own calls, this means that Tracker ends up forming a data structure that records everything that happened during the forward pass (often known as a tape).

    When we call back!(y, [1, -1]), the sensitivities [1, -1] simply get forwarded to y's call (*), effectively calling

    Tracker.back(*, [1, -1], W, x)

    which in turn calculates the sensitivities of the arguments (W and x) and back-propagates through their calls. This is recursive, so it will walk the entire program graph and propagate gradients to the original model parameters.

    diff --git a/v0.6.9/models/basics.html b/v0.6.9/models/basics.html new file mode 100644 index 00000000..6f4c0138 --- /dev/null +++ b/v0.6.9/models/basics.html @@ -0,0 +1,107 @@ + +Basics · Flux

    Basics

    Model-Building Basics

    Taking Gradients

    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.)

    using Flux.Tracker
    +
    +f(x) = 3x^2 + 2x + 1
    +
    +# df/dx = 6x + 2
    +df(x) = Tracker.gradient(f, x)[1]
    +
    +df(2) # 14.0 (tracked)
    +
    +# d²f/dx² = 6
    +d2f(x) = Tracker.gradient(df, x)[1]
    +
    +d2f(2) # 6.0 (tracked)

    (We'll learn more about why these numbers show up as (tracked) below.)

    When a function has many parameters, we can pass them all in explicitly:

    f(W, b, x) = W * x + b
    +
    +Tracker.gradient(f, 2, 3, 4)
    +(4.0 (tracked), 1.0, 2.0 (tracked))

    But machine learning models can have hundreds of parameters! Flux offers a nice way to handle this. We can tell Flux to treat something as a parameter via param. Then we can collect these together and tell gradient to collect the gradients of all of them at once.

    W = param(2) # 2.0 (tracked)
    +b = param(3) # 3.0 (tracked)
    +
    +f(x) = W * x + b
    +
    +params = Params([W, b])
    +grads = Tracker.gradient(() -> f(4), params)
    +
    +grads[W] # 4.0
    +grads[b] # 1.0

    There are a few things to notice here. Firstly, W and b now show up as tracked. Tracked things behave like normal numbers or arrays, but keep records of everything you do with them, allowing Flux to calculate their gradients. gradient takes a zero-argument function; no arguments are necessary because the Params tell it what to differentiate.

    This will come in really handy when dealing with big, complicated models. For now, though, let's start with something simple.

    Simple Models

    Consider a simple linear regression, which tries to predict an output array y from an input x.

    W = rand(2, 5)
    +b = rand(2)
    +
    +predict(x) = W*x .+ b
    +
    +function loss(x, y)
    +  ŷ = predict(x)
    +  sum((y .- ŷ).^2)
    +end
    +
    +x, y = rand(5), rand(2) # Dummy data
    +loss(x, y) # ~ 3

    To improve the prediction we can take the gradients of W and b with respect to the loss and perform gradient descent. Let's tell Flux that W and b are parameters, just like we did above.

    using Flux.Tracker
    +
    +W = param(W)
    +b = param(b)
    +
    +gs = Tracker.gradient(() -> loss(x, y), Params([W, b]))

    Now that we have gradients, we can pull them out and update W to train the model. The update!(W, Δ) function applies W = W + Δ, which we can use for gradient descent.

    using Flux.Tracker: update!
    +
    +Δ = gs[W]
    +
    +# Update the parameter and reset the gradient
    +update!(W, -0.1Δ)
    +
    +loss(x, y) # ~ 2.5

    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.

    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.

    Building Layers

    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:

    W1 = param(rand(3, 5))
    +b1 = param(rand(3))
    +layer1(x) = W1 * x .+ b1
    +
    +W2 = param(rand(2, 3))
    +b2 = param(rand(2))
    +layer2(x) = W2 * x .+ b2
    +
    +model(x) = layer2(σ.(layer1(x)))
    +
    +model(rand(5)) # => 2-element vector

    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.

    function linear(in, out)
    +  W = param(randn(out, in))
    +  b = param(randn(out))
    +  x -> W * x .+ b
    +end
    +
    +linear1 = linear(5, 3) # we can access linear1.W etc
    +linear2 = linear(3, 2)
    +
    +model(x) = linear2(σ.(linear1(x)))
    +
    +model(rand(5)) # => 2-element vector

    Another (equivalent) way is to create a struct that explicitly represents the affine layer.

    struct Affine
    +  W
    +  b
    +end
    +
    +Affine(in::Integer, out::Integer) =
    +  Affine(param(randn(out, in)), param(randn(out)))
    +
    +# Overload call, so the object can be used as a function
    +(m::Affine)(x) = m.W * x .+ m.b
    +
    +a = Affine(10, 5)
    +
    +a(rand(10)) # => 5-element vector

    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.

    (There is one small difference with Dense – for convenience it also takes an activation function, like Dense(10, 5, σ).)

    Stacking It Up

    It's pretty common to write models that look something like:

    layer1 = Dense(10, 5, σ)
    +# ...
    +model(x) = layer3(layer2(layer1(x)))

    For long chains, it might be a bit more intuitive to have a list of layers, like this:

    using Flux
    +
    +layers = [Dense(10, 5, σ), Dense(5, 2), softmax]
    +
    +model(x) = foldl((x, m) -> m(x), layers, init = x)
    +
    +model(rand(10)) # => 2-element vector

    Handily, this is also provided for in Flux:

    model2 = Chain(
    +  Dense(10, 5, σ),
    +  Dense(5, 2),
    +  softmax)
    +
    +model2(rand(10)) # => 2-element vector

    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.

    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.

    m = Dense(5, 2) ∘ Dense(10, 5, σ)
    +
    +m(rand(10))

    Likewise, Chain will happily work with any Julia function.

    m = Chain(x -> x^2, x -> x+1)
    +
    +m(5) # => 26

    Layer helpers

    Flux provides a set of helpers for custom layers, which you can enable by calling

    Flux.@treelike Affine

    This enables a useful extra set of functionality for our Affine layer, such as collecting its parameters or moving it to the GPU.

    diff --git a/v0.6.9/models/layers.html b/v0.6.9/models/layers.html new file mode 100644 index 00000000..41c04e6b --- /dev/null +++ b/v0.6.9/models/layers.html @@ -0,0 +1,38 @@ + +Model Reference · Flux

    Model Reference

    Basic Layers

    These core layers form the foundation of almost all neural networks.

    Flux.ChainType.
    Chain(layers...)

    Chain multiple layers / functions together, so that they are called in sequence on a given input.

    m = Chain(x -> x^2, x -> x+1)
    +m(5) == 26
    +
    +m = Chain(Dense(10, 5), Dense(5, 2))
    +x = rand(10)
    +m(x) == m[2](m[1](x))

    Chain 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.

    source
    Flux.DenseType.
    Dense(in::Integer, out::Integer, σ = identity)

    Creates a traditional Dense layer with parameters W and b.

    y = σ.(W * x .+ b)

    The 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.

    julia> d = Dense(5, 2)
    +Dense(5, 2)
    +
    +julia> d(rand(5))
    +Tracked 2-element Array{Float64,1}:
    +  0.00257447
    +  -0.00449443
    source
    Flux.ConvType.
    Conv(size, in=>out)
    +Conv(size, in=>out, relu)

    Standard convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively.

    Data 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.

    Takes the keyword arguments pad, stride and dilation.

    source
    Flux.MaxPoolType.
    MaxPool(k)

    Max pooling layer. k stands for the size of the window for each dimension of the input.

    Takes the keyword arguments pad and stride.

    source
    Flux.MeanPoolType.
    MeanPool(k)

    Mean pooling layer. k stands for the size of the window for each dimension of the input.

    Takes the keyword arguments pad and stride.

    source

    Additional Convolution Layers

    DepthwiseConv(size, in)
    +DepthwiseConv(size, in=>mul)
    +DepthwiseConv(size, in=>mul, relu)

    Depthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.

    Data 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.

    Takes the keyword arguments pad and stride.

    source

    Recurrent Layers

    Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

    Flux.RNNFunction.
    RNN(in::Integer, out::Integer, σ = tanh)

    The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

    source
    Flux.LSTMFunction.
    LSTM(in::Integer, out::Integer)

    Long Short Term Memory recurrent layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

    See this article for a good overview of the internals.

    source
    Flux.GRUFunction.
    GRU(in::Integer, out::Integer)

    Gated Recurrent Unit layer. Behaves like an RNN but generally exhibits a longer memory span over sequences.

    See this article for a good overview of the internals.

    source
    Flux.RecurType.
    Recur(cell)

    Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

    h, y = cell(h, x...)

    For example, here's a recurrent network that keeps a running total of its inputs.

    accum(h, x) = (h+x, x)
    +rnn = Flux.Recur(accum, 0)
    +rnn(2) # 2
    +rnn(3) # 3
    +rnn.state # 5
    +rnn.(1:10) # apply to a sequence
    +rnn.state # 60
    source

    Activation Functions

    Non-linearities that go between layers of your model. Most of these functions are defined in NNlib but are available by default in Flux.

    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.

    NNlib.σFunction.
    σ(x) = 1 / (1 + exp(-x))

    Classic sigmoid activation function.

    NNlib.reluFunction.
    relu(x) = max(0, x)

    Rectified Linear Unit activation function.

    NNlib.leakyreluFunction.
    leakyrelu(x) = max(0.01x, x)

    Leaky Rectified Linear Unit activation function. You can also specify the coefficient explicitly, e.g. leakyrelu(x, 0.01).

    NNlib.eluFunction.
    elu(x, α = 1) =
    +  x > 0 ? x : α * (exp(x) - 1)

    Exponential 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).

    NNlib.swishFunction.
    swish(x) = x * σ(x)

    Self-gated actvation function. See Swish: a Self-Gated Activation Function.

    Normalisation & Regularisation

    These layers don't affect the structure of the network but may improve training times or reduce overfitting.

    Flux.testmode!Function.
    testmode!(m)
    +testmode!(m, false)

    Put layers like Dropout and BatchNorm into testing mode (or back to training mode with false).

    source
    Flux.BatchNormType.
    BatchNorm(channels::Integer, σ = identity;
    +          initβ = zeros, initγ = ones,
    +          ϵ = 1e-8, momentum = .1)

    Batch Normalization layer. The channels input should be the size of the channel dimension in your data (see below).

    Given 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.)

    BatchNorm 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).

    See Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.

    Example:

    m = Chain(
    +  Dense(28^2, 64),
    +  BatchNorm(64, relu),
    +  Dense(64, 10),
    +  BatchNorm(10),
    +  softmax)
    source
    Flux.DropoutType.
    Dropout(p)

    A Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.

    Does nothing to the input once in testmode!.

    source
    Flux.LayerNormType.
    LayerNorm(h::Integer)

    A 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.

    source
    diff --git a/v0.6.9/models/recurrence.html b/v0.6.9/models/recurrence.html new file mode 100644 index 00000000..d04b07c4 --- /dev/null +++ b/v0.6.9/models/recurrence.html @@ -0,0 +1,42 @@ + +Recurrence · Flux

    Recurrence

    Recurrent Models

    Recurrent Cells

    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.

    y₁ = f(x₁)
    +y₂ = f(x₂)
    +y₃ = f(x₃)
    +# ...

    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.

    h = # ... initial state ...
    +h, y₁ = f(h, x₁)
    +h, y₂ = f(h, x₂)
    +h, y₃ = f(h, x₃)
    +# ...

    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.

    (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".)

    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.

    Wxh = randn(5, 10)
    +Whh = randn(5, 5)
    +b   = randn(5)
    +
    +function rnn(h, x)
    +  h = tanh.(Wxh * x .+ Whh * h .+ b)
    +  return h, h
    +end
    +
    +x = rand(10) # dummy data
    +h = rand(5)  # initial hidden state
    +
    +h, y = rnn(h, x)

    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.

    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:

    using Flux
    +
    +rnn2 = Flux.RNNCell(10, 5)
    +
    +x = rand(10) # dummy data
    +h = rand(5)  # initial hidden state
    +
    +h, y = rnn2(h, x)

    Stateful Models

    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.

    x = rand(10)
    +h = rand(5)
    +
    +m = Flux.Recur(rnn, h)
    +
    +y = m(x)

    The Recur wrapper stores the state between runs in the m.state field.

    If you use the RNN(10, 5) constructor – as opposed to RNNCell – you'll see that it's simply a wrapped cell.

    julia> RNN(10, 5)
    +Recur(RNNCell(Dense(15, 5)))

    Sequences

    Often we want to work with sequences of inputs, rather than individual xs.

    seq = [rand(10) for i = 1:10]

    With Recur, applying our model to each element of a sequence is trivial:

    m.(seq) # returns a list of 5-element vectors

    This works even when we've chain recurrent layers into a larger model.

    m = Chain(LSTM(10, 15), Dense(15, 5))
    +m.(seq)

    Truncating Gradients

    By default, calculating the gradients in a recurrent layer involves its entire history. For example, if we call the model on 100 inputs, we'll have to calculate the gradient for those 100 calls. If we then calculate another 10 inputs we have to calculate 110 gradients – this accumulates and quickly becomes expensive.

    To avoid this we can truncate the gradient calculation, forgetting the history.

    truncate!(m)

    Calling truncate! wipes the slate clean, so we can call the model with more inputs without building up an expensive gradient computation.

    truncate! makes sense when you are working with multiple chunks of a large sequence, but we may also want to work with a set of independent sequences. In this case the hidden state should be completely reset to its original value, throwing away any accumulated information. reset! does this for you.

    diff --git a/v0.6.9/models/regularisation.html b/v0.6.9/models/regularisation.html new file mode 100644 index 00000000..2f6f7b38 --- /dev/null +++ b/v0.6.9/models/regularisation.html @@ -0,0 +1,35 @@ + +Regularisation · Flux

    Regularisation

    Regularisation

    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.

    For example, say we have a simple regression.

    using Flux: crossentropy
    +m = Dense(10, 5)
    +loss(x, y) = crossentropy(softmax(m(x)), y)

    We can regularise this by taking the (L2) norm of the parameters, m.W and m.b.

    penalty() = norm(m.W) + norm(m.b)
    +loss(x, y) = crossentropy(softmax(m(x)), y) + penalty()

    When working with layers, Flux provides the params function to grab all parameters at once. We can easily penalise everything with sum(norm, params).

    julia> params(m)
    +2-element Array{Any,1}:
    + param([0.355408 0.533092; … 0.430459 0.171498])
    + param([0.0, 0.0, 0.0, 0.0, 0.0])
    +
    +julia> sum(norm, params(m))
    +26.01749952921026 (tracked)

    Here's a larger example with a multi-layer perceptron.

    m = Chain(
    +  Dense(28^2, 128, relu),
    +  Dense(128, 32, relu),
    +  Dense(32, 10), softmax)
    +
    +loss(x, y) = crossentropy(m(x), y) + sum(norm, params(m))
    +
    +loss(rand(28^2), rand(10))

    One can also easily add per-layer regularisation via the activations function:

    julia> c = Chain(Dense(10,5,σ),Dense(5,2),softmax)
    +Chain(Dense(10, 5, NNlib.σ), Dense(5, 2), NNlib.softmax)
    +
    +julia> activations(c, rand(10))
    +3-element Array{Any,1}:
    + param([0.71068, 0.831145, 0.751219, 0.227116, 0.553074])
    + param([0.0330606, -0.456104])
    + param([0.61991, 0.38009])
    +
    +julia> sum(norm, ans)
    +2.639678767773633 (tracked)
    diff --git a/v0.6.9/saving.html b/v0.6.9/saving.html new file mode 100644 index 00000000..a3694ffa --- /dev/null +++ b/v0.6.9/saving.html @@ -0,0 +1,50 @@ + +Saving & Loading · Flux

    Saving & Loading

    Saving and Loading Models

    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.

    Save a model:

    julia> using Flux
    +
    +julia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)
    +Chain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)
    +
    +julia> using BSON: @save
    +
    +julia> @save "mymodel.bson" model

    Load it again:

    julia> using Flux
    +
    +julia> using BSON: @load
    +
    +julia> @load "mymodel.bson" model
    +
    +julia> model
    +Chain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)

    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).

    Note

    If 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.

    Saving Model Weights

    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.

    julia> using Flux
    +
    +julia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)
    +Chain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)
    +
    +julia> weights = Tracker.data.(params(model));
    +
    +julia> using BSON: @save
    +
    +julia> @save "mymodel.bson" weights

    You can easily load parameters back into a model with Flux.loadparams!.

    julia> using Flux
    +
    +julia> model = Chain(Dense(10,5,relu),Dense(5,2),softmax)
    +Chain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax)
    +
    +julia> using BSON: @load
    +
    +julia> @load "mymodel.bson" weights
    +
    +julia> Flux.loadparams!(model, weights)

    The new model we created will now be identical to the one we saved parameters for.

    Checkpointing

    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!.

    using Flux: throttle
    +using BSON: @save
    +
    +m = Chain(Dense(10,5,relu),Dense(5,2),softmax)
    +
    +evalcb = throttle(30) do
    +  # Show loss
    +  @save "model-checkpoint.bson" model
    +end

    This will update the "model-checkpoint.bson" file every thirty seconds.

    You can get more advanced by saving a series of models throughout training, for example

    @save "model-$(now()).bson" model

    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.

    @save "model-$(now()).bson" model loss = testloss()

    You can even store optimiser state alongside the model, to resume training exactly where you left off.

    opt = ADAM(params(model))
    +@save "model-$(now()).bson" model opt
    diff --git a/v0.6.9/search.html b/v0.6.9/search.html new file mode 100644 index 00000000..00437b2e --- /dev/null +++ b/v0.6.9/search.html @@ -0,0 +1,9 @@ + +Search · Flux

    Search

    Search

    Number of results: loading...

      diff --git a/v0.6.9/search_index.js b/v0.6.9/search_index.js new file mode 100644 index 00000000..03a537ea --- /dev/null +++ b/v0.6.9/search_index.js @@ -0,0 +1,555 @@ +var documenterSearchIndex = {"docs": [ + +{ + "location": "index.html#", + "page": "Home", + "title": "Home", + "category": "page", + "text": "" +}, + +{ + "location": "index.html#Flux:-The-Julia-Machine-Learning-Library-1", + "page": "Home", + "title": "Flux: The Julia Machine Learning Library", + "category": "section", + "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: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." +}, + +{ + "location": "index.html#Installation-1", + "page": "Home", + "title": "Installation", + "category": "section", + "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.If you have CUDA you can also run ] add CuArrays to get GPU support; see here for more details." +}, + +{ + "location": "index.html#Learning-Flux-1", + "page": "Home", + "title": "Learning Flux", + "category": "section", + "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." +}, + +{ + "location": "models/basics.html#", + "page": "Basics", + "title": "Basics", + "category": "page", + "text": "" +}, + +{ + "location": "models/basics.html#Model-Building-Basics-1", + "page": "Basics", + "title": "Model-Building Basics", + "category": "section", + "text": "" +}, + +{ + "location": "models/basics.html#Taking-Gradients-1", + "page": "Basics", + "title": "Taking Gradients", + "category": "section", + "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.)using Flux.Tracker\n\nf(x) = 3x^2 + 2x + 1\n\n# df/dx = 6x + 2\ndf(x) = Tracker.gradient(f, x)[1]\n\ndf(2) # 14.0 (tracked)\n\n# d²f/dx² = 6\nd2f(x) = Tracker.gradient(df, x)[1]\n\nd2f(2) # 6.0 (tracked)(We\'ll learn more about why these numbers show up as (tracked) below.)When a function has many parameters, we can pass them all in explicitly:f(W, b, x) = W * x + b\n\nTracker.gradient(f, 2, 3, 4)\n(4.0 (tracked), 1.0, 2.0 (tracked))But machine learning models can have hundreds of parameters! Flux offers a nice way to handle this. We can tell Flux to treat something as a parameter via param. Then we can collect these together and tell gradient to collect the gradients of all of them at once.W = param(2) # 2.0 (tracked)\nb = param(3) # 3.0 (tracked)\n\nf(x) = W * x + b\n\nparams = Params([W, b])\ngrads = Tracker.gradient(() -> f(4), params)\n\ngrads[W] # 4.0\ngrads[b] # 1.0There are a few things to notice here. Firstly, W and b now show up as tracked. Tracked things behave like normal numbers or arrays, but keep records of everything you do with them, allowing Flux to calculate their gradients. gradient takes a zero-argument function; no arguments are necessary because the Params tell it what to differentiate.This will come in really handy when dealing with big, complicated models. For now, though, let\'s start with something simple." +}, + +{ + "location": "models/basics.html#Simple-Models-1", + "page": "Basics", + "title": "Simple Models", + "category": "section", + "text": "Consider a simple linear regression, which tries to predict an output array y from an input x.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) # ~ 3To improve the prediction we can take the gradients of W and b with respect to the loss and perform gradient descent. Let\'s tell Flux that W and b are parameters, just like we did above.using Flux.Tracker\n\nW = param(W)\nb = param(b)\n\ngs = Tracker.gradient(() -> loss(x, y), Params([W, b]))Now that we have gradients, we can pull them out and update W to train the model. The update!(W, Δ) function applies W = W + Δ, which we can use for gradient descent.using Flux.Tracker: update!\n\nΔ = gs[W]\n\n# Update the parameter and reset the gradient\nupdate!(W, -0.1Δ)\n\nloss(x, y) # ~ 2.5The 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.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." +}, + +{ + "location": "models/basics.html#Building-Layers-1", + "page": "Basics", + "title": "Building Layers", + "category": "section", + "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:W1 = param(rand(3, 5))\nb1 = param(rand(3))\nlayer1(x) = W1 * x .+ b1\n\nW2 = param(rand(2, 3))\nb2 = param(rand(2))\nlayer2(x) = W2 * x .+ b2\n\nmodel(x) = layer2(σ.(layer1(x)))\n\nmodel(rand(5)) # => 2-element vectorThis 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.function linear(in, out)\n W = param(randn(out, in))\n b = param(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 vectorAnother (equivalent) way is to create a struct that explicitly represents the affine layer.struct Affine\n W\n b\nend\n\nAffine(in::Integer, out::Integer) =\n Affine(param(randn(out, in)), param(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 vectorCongratulations! 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.(There is one small difference with Dense – for convenience it also takes an activation function, like Dense(10, 5, σ).)" +}, + +{ + "location": "models/basics.html#Stacking-It-Up-1", + "page": "Basics", + "title": "Stacking It Up", + "category": "section", + "text": "It\'s pretty common to write models that look something like:layer1 = Dense(10, 5, σ)\n# ...\nmodel(x) = layer3(layer2(layer1(x)))For long chains, it might be a bit more intuitive to have a list of layers, like this: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 vectorHandily, this is also provided for in Flux:model2 = Chain(\n Dense(10, 5, σ),\n Dense(5, 2),\n softmax)\n\nmodel2(rand(10)) # => 2-element vectorThis 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.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.m = Dense(5, 2) ∘ Dense(10, 5, σ)\n\nm(rand(10))Likewise, Chain will happily work with any Julia function.m = Chain(x -> x^2, x -> x+1)\n\nm(5) # => 26" +}, + +{ + "location": "models/basics.html#Layer-helpers-1", + "page": "Basics", + "title": "Layer helpers", + "category": "section", + "text": "Flux provides a set of helpers for custom layers, which you can enable by callingFlux.@treelike AffineThis enables a useful extra set of functionality for our Affine layer, such as collecting its parameters or moving it to the GPU." +}, + +{ + "location": "models/recurrence.html#", + "page": "Recurrence", + "title": "Recurrence", + "category": "page", + "text": "" +}, + +{ + "location": "models/recurrence.html#Recurrent-Models-1", + "page": "Recurrence", + "title": "Recurrent Models", + "category": "section", + "text": "" +}, + +{ + "location": "models/recurrence.html#Recurrent-Cells-1", + "page": "Recurrence", + "title": "Recurrent Cells", + "category": "section", + "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.y₁ = f(x₁)\ny₂ = f(x₂)\ny₃ = f(x₃)\n# ...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.h = # ... initial state ...\nh, y₁ = f(h, x₁)\nh, y₂ = f(h, x₂)\nh, y₃ = f(h, x₃)\n# ...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.(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\".)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.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)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.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: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)" +}, + +{ + "location": "models/recurrence.html#Stateful-Models-1", + "page": "Recurrence", + "title": "Stateful Models", + "category": "section", + "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.x = rand(10)\nh = rand(5)\n\nm = Flux.Recur(rnn, h)\n\ny = m(x)The Recur wrapper stores the state between runs in the m.state field.If you use the RNN(10, 5) constructor – as opposed to RNNCell – you\'ll see that it\'s simply a wrapped cell.julia> RNN(10, 5)\nRecur(RNNCell(Dense(15, 5)))" +}, + +{ + "location": "models/recurrence.html#Sequences-1", + "page": "Recurrence", + "title": "Sequences", + "category": "section", + "text": "Often we want to work with sequences of inputs, rather than individual xs.seq = [rand(10) for i = 1:10]With Recur, applying our model to each element of a sequence is trivial:m.(seq) # returns a list of 5-element vectorsThis works even when we\'ve chain recurrent layers into a larger model.m = Chain(LSTM(10, 15), Dense(15, 5))\nm.(seq)" +}, + +{ + "location": "models/recurrence.html#Truncating-Gradients-1", + "page": "Recurrence", + "title": "Truncating Gradients", + "category": "section", + "text": "By default, calculating the gradients in a recurrent layer involves its entire history. For example, if we call the model on 100 inputs, we\'ll have to calculate the gradient for those 100 calls. If we then calculate another 10 inputs we have to calculate 110 gradients – this accumulates and quickly becomes expensive.To avoid this we can truncate the gradient calculation, forgetting the history.truncate!(m)Calling truncate! wipes the slate clean, so we can call the model with more inputs without building up an expensive gradient computation.truncate! makes sense when you are working with multiple chunks of a large sequence, but we may also want to work with a set of independent sequences. In this case the hidden state should be completely reset to its original value, throwing away any accumulated information. reset! does this for you." +}, + +{ + "location": "models/regularisation.html#", + "page": "Regularisation", + "title": "Regularisation", + "category": "page", + "text": "" +}, + +{ + "location": "models/regularisation.html#Regularisation-1", + "page": "Regularisation", + "title": "Regularisation", + "category": "section", + "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.For example, say we have a simple regression.using Flux: crossentropy\nm = Dense(10, 5)\nloss(x, y) = crossentropy(softmax(m(x)), y)We can regularise this by taking the (L2) norm of the parameters, m.W and m.b.penalty() = norm(m.W) + norm(m.b)\nloss(x, y) = crossentropy(softmax(m(x)), y) + penalty()When working with layers, Flux provides the params function to grab all parameters at once. We can easily penalise everything with sum(norm, params).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)Here\'s a larger example with a multi-layer perceptron.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))One can also easily add per-layer regularisation via the activations function:julia> c = Chain(Dense(10,5,σ),Dense(5,2),softmax)\nChain(Dense(10, 5, NNlib.σ), Dense(5, 2), NNlib.softmax)\n\njulia> activations(c, rand(10))\n3-element Array{Any,1}:\n param([0.71068, 0.831145, 0.751219, 0.227116, 0.553074])\n param([0.0330606, -0.456104])\n param([0.61991, 0.38009])\n\njulia> sum(norm, ans)\n2.639678767773633 (tracked)" +}, + +{ + "location": "models/layers.html#", + "page": "Model Reference", + "title": "Model Reference", + "category": "page", + "text": "" +}, + +{ + "location": "models/layers.html#Flux.Chain", + "page": "Model Reference", + "title": "Flux.Chain", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Flux.Dense", + "page": "Model Reference", + "title": "Flux.Dense", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Flux.Conv", + "page": "Model Reference", + "title": "Flux.Conv", + "category": "type", + "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\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" +}, + +{ + "location": "models/layers.html#Flux.MaxPool", + "page": "Model Reference", + "title": "Flux.MaxPool", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Flux.MeanPool", + "page": "Model Reference", + "title": "Flux.MeanPool", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Basic-Layers-1", + "page": "Model Reference", + "title": "Basic Layers", + "category": "section", + "text": "These core layers form the foundation of almost all neural networks.Chain\nDense\nConv\nMaxPool\nMeanPool" +}, + +{ + "location": "models/layers.html#Flux.DepthwiseConv", + "page": "Model Reference", + "title": "Flux.DepthwiseConv", + "category": "type", + "text": "DepthwiseConv(size, in)\nDepthwiseConv(size, in=>mul)\nDepthwiseConv(size, in=>mul, relu)\n\nDepthwise convolutional layer. size should be a tuple like (2, 2). in and mul specify the number of input channels and channel multiplier respectively. In case the mul is not specified it is taken as 1.\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 and stride.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Additional-Convolution-Layers-1", + "page": "Model Reference", + "title": "Additional Convolution Layers", + "category": "section", + "text": "DepthwiseConv" +}, + +{ + "location": "models/layers.html#Flux.RNN", + "page": "Model Reference", + "title": "Flux.RNN", + "category": "function", + "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" +}, + +{ + "location": "models/layers.html#Flux.LSTM", + "page": "Model Reference", + "title": "Flux.LSTM", + "category": "function", + "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" +}, + +{ + "location": "models/layers.html#Flux.GRU", + "page": "Model Reference", + "title": "Flux.GRU", + "category": "function", + "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" +}, + +{ + "location": "models/layers.html#Flux.Recur", + "page": "Model Reference", + "title": "Flux.Recur", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Recurrent-Layers-1", + "page": "Model Reference", + "title": "Recurrent Layers", + "category": "section", + "text": "Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).RNN\nLSTM\nGRU\nFlux.Recur" +}, + +{ + "location": "models/layers.html#NNlib.σ", + "page": "Model Reference", + "title": "NNlib.σ", + "category": "function", + "text": "σ(x) = 1 / (1 + exp(-x))\n\nClassic sigmoid activation function.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#NNlib.relu", + "page": "Model Reference", + "title": "NNlib.relu", + "category": "function", + "text": "relu(x) = max(0, x)\n\nRectified Linear Unit activation function.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#NNlib.leakyrelu", + "page": "Model Reference", + "title": "NNlib.leakyrelu", + "category": "function", + "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" +}, + +{ + "location": "models/layers.html#NNlib.elu", + "page": "Model Reference", + "title": "NNlib.elu", + "category": "function", + "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" +}, + +{ + "location": "models/layers.html#NNlib.swish", + "page": "Model Reference", + "title": "NNlib.swish", + "category": "function", + "text": "swish(x) = x * σ(x)\n\nSelf-gated actvation function. See Swish: a Self-Gated Activation Function.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Activation-Functions-1", + "page": "Model Reference", + "title": "Activation Functions", + "category": "section", + "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.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.σ\nrelu\nleakyrelu\nelu\nswish" +}, + +{ + "location": "models/layers.html#Flux.testmode!", + "page": "Model Reference", + "title": "Flux.testmode!", + "category": "function", + "text": "testmode!(m)\ntestmode!(m, false)\n\nPut layers like Dropout and BatchNorm into testing mode (or back to training mode with false).\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Flux.BatchNorm", + "page": "Model Reference", + "title": "Flux.BatchNorm", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Flux.Dropout", + "page": "Model Reference", + "title": "Flux.Dropout", + "category": "type", + "text": "Dropout(p)\n\nA Dropout layer. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). This is used as a regularisation, i.e. it reduces overfitting during training.\n\nDoes nothing to the input once in testmode!.\n\n\n\n\n\n" +}, + +{ + "location": "models/layers.html#Flux.LayerNorm", + "page": "Model Reference", + "title": "Flux.LayerNorm", + "category": "type", + "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" +}, + +{ + "location": "models/layers.html#Normalisation-and-Regularisation-1", + "page": "Model Reference", + "title": "Normalisation & Regularisation", + "category": "section", + "text": "These layers don\'t affect the structure of the network but may improve training times or reduce overfitting.Flux.testmode!\nBatchNorm\nDropout\nLayerNorm" +}, + +{ + "location": "training/optimisers.html#", + "page": "Optimisers", + "title": "Optimisers", + "category": "page", + "text": "" +}, + +{ + "location": "training/optimisers.html#Optimisers-1", + "page": "Optimisers", + "title": "Optimisers", + "category": "section", + "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.using Flux.Tracker\n\nW = param(rand(2, 5))\nb = param(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\nparams = Params([W, b])\ngrads = Tracker.gradient(() -> loss(x, y), params)We want to update each parameter, using the gradient, in order to improve (reduce) the loss. Here\'s one way to do that:using Flux.Tracker: grad, update!\n\nfunction sgd()\n η = 0.1 # Learning Rate\n for p in (W, b)\n update!(p, -η * grads[p])\n end\nendIf we call sgd, the parameters W and b will change and our loss should go down.There are two pieces here: one is that we need a list of trainable parameters for the model ([W, b] in this case), and the other is the update step. In this case the update is simply gradient descent (x .-= η .* Δ), but we might choose to do something more advanced, like adding momentum.In this case, getting the variables is trivial, but you can imagine it\'d be more of a pain with some complex stack of layers.m = Chain(\n Dense(10, 5, σ),\n Dense(5, 2), softmax)Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.For the update step, there\'s nothing whatsoever wrong with writing the loop above – it\'ll work just fine – but Flux provides various optimisers that make it more convenient.opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1\n\nopt() # Carry out the update, modifying `W` and `b`.An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data." +}, + +{ + "location": "training/optimisers.html#Optimiser-Reference-1", + "page": "Optimisers", + "title": "Optimiser Reference", + "category": "section", + "text": "All optimisers return a function that, when called, will update the parameters passed to it.SGD\nMomentum\nNesterov\nADAM" +}, + +{ + "location": "training/training.html#", + "page": "Training", + "title": "Training", + "category": "page", + "text": "" +}, + +{ + "location": "training/training.html#Training-1", + "page": "Training", + "title": "Training", + "category": "section", + "text": "To actually train a model we need three things:A objective function, that evaluates how well a model is doing given some input data.\nA collection of data points that will be provided to the objective function.\nAn optimiser that will update the model parameters appropriately.With these we can call Flux.train!:Flux.train!(objective, data, opt)There are plenty of examples in the model zoo." +}, + +{ + "location": "training/training.html#Loss-Functions-1", + "page": "Training", + "title": "Loss Functions", + "category": "section", + "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:m = Chain(\n Dense(784, 32, σ),\n Dense(32, 10), softmax)\n\nloss(x, y) = Flux.mse(m(x), y)\n\n# later\nFlux.train!(loss, data, opt)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." +}, + +{ + "location": "training/training.html#Datasets-1", + "page": "Training", + "title": "Datasets", + "category": "section", + "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:x = rand(784)\ny = rand(10)\ndata = [(x, y)]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:data = [(x, y), (x, y), (x, y)]\n# Or equivalently\ndata = Iterators.repeated((x, y), 3)It\'s common to load the xs and ys separately. In this case you can use zip:xs = [rand(784), rand(784), rand(784)]\nys = [rand( 10), rand( 10), rand( 10)]\ndata = zip(xs, ys)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.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" +}, + +{ + "location": "training/training.html#Callbacks-1", + "page": "Training", + "title": "Callbacks", + "category": "section", + "text": "train! takes an additional argument, cb, that\'s used for callbacks so that you can observe the training process. For example:train!(objective, data, opt, cb = () -> println(\"training\"))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.A more typical callback might look like this:test_x, test_y = # ... create single batch of test data ...\nevalcb() = @show(loss(test_x, test_y))\n\nFlux.train!(objective, data, opt,\n cb = throttle(evalcb, 5))" +}, + +{ + "location": "data/onehot.html#", + "page": "One-Hot Encoding", + "title": "One-Hot Encoding", + "category": "page", + "text": "" +}, + +{ + "location": "data/onehot.html#One-Hot-Encoding-1", + "page": "One-Hot Encoding", + "title": "One-Hot Encoding", + "category": "section", + "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.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 trueThe inverse is onecold (which can take a general probability distribution, as well as just booleans).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" +}, + +{ + "location": "data/onehot.html#Batches-1", + "page": "One-Hot Encoding", + "title": "Batches", + "category": "section", + "text": "onehotbatch creates a batch (matrix) of one-hot vectors, and onecold treats matrices as batches.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 :bNote 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." +}, + +{ + "location": "gpu.html#", + "page": "GPU Support", + "title": "GPU Support", + "category": "page", + "text": "" +}, + +{ + "location": "gpu.html#GPU-Support-1", + "page": "GPU Support", + "title": "GPU Support", + "category": "section", + "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.For example, we can use CuArrays (with the cu converter) to run our basic example on an NVIDIA GPU.(Note that you need to build Julia 0.6 from source and have CUDA available to use CuArrays – please see the CUDAnative.jl instructions for more details.)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) # ~ 3Note 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.If you define a structured model, like a Dense layer or Chain, you just need to convert the internal parameters. Flux provides mapleaves, which allows you to alter all parameters of a model at once.d = Dense(10, 5, σ)\nd = mapleaves(cu, d)\nd.W # Tracked CuArray\nd(cu(rand(10))) # CuArray output\n\nm = Chain(Dense(10, 5, σ), Dense(5, 2), softmax)\nm = mapleaves(cu, m)\nd(cu(rand(10)))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.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.618002The analogue cpu is also available for moving models and data back off of the GPU.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" +}, + +{ + "location": "saving.html#", + "page": "Saving & Loading", + "title": "Saving & Loading", + "category": "page", + "text": "" +}, + +{ + "location": "saving.html#Saving-and-Loading-Models-1", + "page": "Saving & Loading", + "title": "Saving and Loading Models", + "category": "section", + "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.Save a model: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\" modelLoad it again: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)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).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." +}, + +{ + "location": "saving.html#Saving-Model-Weights-1", + "page": "Saving & Loading", + "title": "Saving Model Weights", + "category": "section", + "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.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 = Tracker.data.(params(model));\n\njulia> using BSON: @save\n\njulia> @save \"mymodel.bson\" weightsYou can easily load parameters back into a model with Flux.loadparams!.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)The new model we created will now be identical to the one we saved parameters for." +}, + +{ + "location": "saving.html#Checkpointing-1", + "page": "Saving & Loading", + "title": "Checkpointing", + "category": "section", + "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!.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\nendThis will update the \"model-checkpoint.bson\" file every thirty seconds.You can get more advanced by saving a series of models throughout training, for example@save \"model-$(now()).bson\" modelwill 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.@save \"model-$(now()).bson\" model loss = testloss()You can even store optimiser state alongside the model, to resume training exactly where you left off.opt = ADAM(params(model))\n@save \"model-$(now()).bson\" model opt" +}, + +{ + "location": "internals/tracker.html#", + "page": "Backpropagation", + "title": "Backpropagation", + "category": "page", + "text": "" +}, + +{ + "location": "internals/tracker.html#Flux.Tracker-1", + "page": "Backpropagation", + "title": "Flux.Tracker", + "category": "section", + "text": "Backpropagation, or reverse-mode automatic differentiation, is handled by the Flux.Tracker module.julia> using Flux.TrackerHere we discuss some more advanced uses of this module, as well as covering its internals." +}, + +{ + "location": "internals/tracker.html#Taking-Gradients-1", + "page": "Backpropagation", + "title": "Taking Gradients", + "category": "section", + "text": "In the basics section we covered basic usage of the gradient function.using Flux.Tracker\n\nTracker.gradient((a, b) -> a*b, 2, 3) # (3.0 (tracked), 2.0 (tracked))gradient is actually just a thin wrapper around the backpropagator-based interface, forward.using Flux.Tracker: forward\n\ny, back = forward((a, b) -> a*b, 2, 3) # (6.0 (tracked), Flux.Tracker.#9)\n\nback(1) # (3.0 (tracked), 2.0 (tracked))The forward function returns two results. The first, y, is the original value of the function (perhaps with tracking applied). The second, back, is a new function which, given a sensitivity, returns the sensitivity of the inputs to forward (we call this a \"backpropagator\"). One use of this interface is to provide custom sensitivities when outputs are not scalar.julia> y, back = forward((a, b) -> a.*b, [1,2,3],[4,5,6])\n(param([4.0, 10.0, 18.0]), Flux.Tracker.#9)\n\njulia> back([1,1,1])\n(param([4.0, 5.0, 6.0]), param([1.0, 2.0, 3.0]))We can also take gradients in-place. This can be useful if you only care about first-order gradients.a, b = param(2), param(3)\n\nc = a*b # 6.0 (tracked)\n\nTracker.back!(c)\n\nTracker.grad(a), Tracker.grad(b) # (3.0, 2.0)" +}, + +{ + "location": "internals/tracker.html#Tracked-Arrays-1", + "page": "Backpropagation", + "title": "Tracked Arrays", + "category": "section", + "text": "The param function converts a normal Julia array into a new object that, while behaving like an array, tracks extra information that allows us to calculate derivatives. For example, say we multiply two parameters:julia> W = param([1 2; 3 4])\nTracked 2×2 Array{Float64,2}:\n 1.0 2.0\n 3.0 4.0\n\njulia> x = param([5, 6])\nTracked 2-element Array{Float64,1}:\n 5.0\n 6.0\n\njulia> y = W*x\nTracked 2-element Array{Float64,1}:\n 17.0\n 39.0The output y is also a TrackedArray object. We can now backpropagate sensitivities to W and x via the back! function, and see the gradients accumulated in the W and x tracked arrays:julia> Tracker.back!(y, [1, -1])\n\njulia> W.grad\n2×2 Array{Float64,2}:\n 5.0 6.0\n-5.0 -6.0\n\njulia> x.grad\n2-element Array{Float64,1}:\n -2.0\n -2.0You may sometimes want to drop derivative information and just get the plain value back. You can do this by calling Tracker.data(W)." +}, + +{ + "location": "internals/tracker.html#Custom-Gradients-1", + "page": "Backpropagation", + "title": "Custom Gradients", + "category": "section", + "text": "We can hook in to the processes above to implement custom gradients for a function or kernel. For a toy example, imagine a custom implementation of minus:minus(a, b) = a - bFirstly, we must tell the tracker system to stop when it sees a call to minus, and record it. We can do this using dispatch:using Flux.Tracker: TrackedArray, track, @grad\n\nminus(a::TrackedArray, b::TrackedArray) = track(minus, a, b)track takes care of building a new Tracked object and recording the operation on the tape. We just need to provide a gradient definition.@grad function minus(a, b)\n return minus(data(a), data(b)), Δ -> (Δ, -Δ)\nendThis is essentially just a way of overloading the forward function we saw above. We strip tracking from a and b so that we are calling the original definition of minus (otherwise, we\'d just try to track the call again and hit an infinite regress).Note that in the backpropagator we don\'t call data(a); we do in fact want to track this, since nest AD will take a derivative through the backpropagator itself. For example, the gradient of * might look like this.@grad a * b = data(a)*data(b), Δ -> (Δ*b, a*Δ)We can then calculate the first derivative of minus as follows:a = param([1,2,3])\nb = param([3,2,1])\n\nc = minus(a, b) # [-2.0 (tracked), 0.0 (tracked), 2.0 (tracked)]\n\nTracker.back!(c, 1)\nTracker.grad(a) # [1.00, 1.00, 1.00]\nTracker.grad(b) # [-1.00, -1.00, -1.00]For multi-argument functions with custom gradients, you likely want to catch not just minus(::TrackedArray, ::TrackedArray) but also minus(::Array, TrackedArray) and so on. To do so, just define those extra signatures as needed:minus(a::AbstractArray, b::TrackedArray) = Tracker.track(minus, a, b)\nminus(a::TrackedArray, b::AbstractArray) = Tracker.track(minus, a, b)" +}, + +{ + "location": "internals/tracker.html#Tracked-Internals-1", + "page": "Backpropagation", + "title": "Tracked Internals", + "category": "section", + "text": "All Tracked* objects (TrackedArray, TrackedReal) are light wrappers around the Tracked type, which you can access via the .tracker field.julia> x.tracker\nFlux.Tracker.Tracked{Array{Float64,1}}(0x00000000, Flux.Tracker.Call{Nothing,Tuple{}}(nothing, ()), true, [5.0, 6.0], [-2.0, -2.0])The Tracker stores the gradient of a given object, which we\'ve seen before.julia> x.tracker.grad\n2-element Array{Float64,1}:\n -2.0\n -2.0The tracker also contains a Call object, which simply represents a function call that was made at some point during the forward pass. For example, the + call would look like this:julia> Tracker.Call(+, 1, 2)\nFlux.Tracker.Call{Base.#+,Tuple{Int64,Int64}}(+, (1, 2))In the case of the y we produced above, we can see that it stores the call that produced it – that is, W*x.julia> y.tracker.f\nFlux.Tracker.Call{...}(*, (param([1.0 2.0; 3.0 4.0]), param([5.0, 6.0])))Notice that because the arguments to the call may also be tracked arrays, storing their own calls, this means that Tracker ends up forming a data structure that records everything that happened during the forward pass (often known as a tape).When we call back!(y, [1, -1]), the sensitivities [1, -1] simply get forwarded to y\'s call (*), effectively callingTracker.back(*, [1, -1], W, x)which in turn calculates the sensitivities of the arguments (W and x) and back-propagates through their calls. This is recursive, so it will walk the entire program graph and propagate gradients to the original model parameters." +}, + +{ + "location": "community.html#", + "page": "Community", + "title": "Community", + "category": "page", + "text": "" +}, + +{ + "location": "community.html#Community-1", + "page": "Community", + "title": "Community", + "category": "section", + "text": "All Flux users are welcome to join our community on the Julia forum, the slack (channel #machine-learning), or Flux\'s Gitter. If you have questions or issues we\'ll try to help you out.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." +}, + +]} diff --git a/v0.6.9/siteinfo.js b/v0.6.9/siteinfo.js new file mode 100644 index 00000000..48993900 --- /dev/null +++ b/v0.6.9/siteinfo.js @@ -0,0 +1 @@ +var DOCUMENTER_CURRENT_VERSION = "v0.6.9"; diff --git a/v0.6.9/training/optimisers.html b/v0.6.9/training/optimisers.html new file mode 100644 index 00000000..c08db2d7 --- /dev/null +++ b/v0.6.9/training/optimisers.html @@ -0,0 +1,35 @@ + +Optimisers · Flux

      Optimisers

      Optimisers

      Consider a simple linear regression. We create some dummy data, calculate a loss, and backpropagate to calculate gradients for the parameters W and b.

      using Flux.Tracker
      +
      +W = param(rand(2, 5))
      +b = param(rand(2))
      +
      +predict(x) = W*x .+ b
      +loss(x, y) = sum((predict(x) .- y).^2)
      +
      +x, y = rand(5), rand(2) # Dummy data
      +l = loss(x, y) # ~ 3
      +
      +params = Params([W, b])
      +grads = Tracker.gradient(() -> loss(x, y), params)

      We want to update each parameter, using the gradient, in order to improve (reduce) the loss. Here's one way to do that:

      using Flux.Tracker: grad, update!
      +
      +function sgd()
      +  η = 0.1 # Learning Rate
      +  for p in (W, b)
      +    update!(p, -η * grads[p])
      +  end
      +end

      If we call sgd, the parameters W and b will change and our loss should go down.

      There are two pieces here: one is that we need a list of trainable parameters for the model ([W, b] in this case), and the other is the update step. In this case the update is simply gradient descent (x .-= η .* Δ), but we might choose to do something more advanced, like adding momentum.

      In this case, getting the variables is trivial, but you can imagine it'd be more of a pain with some complex stack of layers.

      m = Chain(
      +  Dense(10, 5, σ),
      +  Dense(5, 2), softmax)

      Instead of having to write [m[1].W, m[1].b, ...], Flux provides a params function params(m) that returns a list of all parameters in the model for you.

      For the update step, there's nothing whatsoever wrong with writing the loop above – it'll work just fine – but Flux provides various optimisers that make it more convenient.

      opt = SGD([W, b], 0.1) # Gradient descent with learning rate 0.1
      +
      +opt() # Carry out the update, modifying `W` and `b`.

      An optimiser takes a parameter list and returns a function that does the same thing as update above. We can pass either opt or update to our training loop, which will then run the optimiser after every mini-batch of data.

      Optimiser Reference

      All optimisers return a function that, when called, will update the parameters passed to it.

      SGD
      +Momentum
      +Nesterov
      +ADAM
      diff --git a/v0.6.9/training/training.html b/v0.6.9/training/training.html new file mode 100644 index 00000000..3e64dad5 --- /dev/null +++ b/v0.6.9/training/training.html @@ -0,0 +1,35 @@ + +Training · Flux

      Training

      Training

      To actually train a model we need three things:

      • A objective function, that evaluates how well a model is doing given some input data.
      • A collection of data points that will be provided to the objective function.
      • An optimiser that will update the model parameters appropriately.

      With these we can call Flux.train!:

      Flux.train!(objective, data, opt)

      There are plenty of examples in the model zoo.

      Loss Functions

      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:

      m = Chain(
      +  Dense(784, 32, σ),
      +  Dense(32, 10), softmax)
      +
      +loss(x, y) = Flux.mse(m(x), y)
      +
      +# later
      +Flux.train!(loss, data, opt)

      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.

      Datasets

      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:

      x = rand(784)
      +y = rand(10)
      +data = [(x, y)]

      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:

      data = [(x, y), (x, y), (x, y)]
      +# Or equivalently
      +data = Iterators.repeated((x, y), 3)

      It's common to load the xs and ys separately. In this case you can use zip:

      xs = [rand(784), rand(784), rand(784)]
      +ys = [rand( 10), rand( 10), rand( 10)]
      +data = zip(xs, ys)

      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.

      julia> using Flux: @epochs
      +
      +julia> @epochs 2 println("hello")
      +INFO: Epoch 1
      +hello
      +INFO: Epoch 2
      +hello
      +
      +julia> @epochs 2 Flux.train!(...)
      +# Train for two epochs

      Callbacks

      train! takes an additional argument, cb, that's used for callbacks so that you can observe the training process. For example:

      train!(objective, data, opt, cb = () -> println("training"))

      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.

      A more typical callback might look like this:

      test_x, test_y = # ... create single batch of test data ...
      +evalcb() = @show(loss(test_x, test_y))
      +
      +Flux.train!(objective, data, opt,
      +            cb = throttle(evalcb, 5))
      diff --git a/versions.js b/versions.js index 2f01d7e8..d457508c 100644 --- a/versions.js +++ b/versions.js @@ -7,6 +7,7 @@ var DOC_VERSIONS = [ "release-0.3", "release-0.2", "release-0.1", + "v0.6.9", "v0.6.8", "v0.6.7", "v0.5.4",