diff --git a/dev/data/dataloader/index.html b/dev/data/dataloader/index.html index 868f9e9b..f3faeaab 100644 --- a/dev/data/dataloader/index.html +++ b/dev/data/dataloader/index.html @@ -27,4 +27,4 @@ end # train for 10 epochs using IterTools: ncycle -Flux.train!(loss, ps, ncycle(dtrain, 10), opt)source +Flux.train!(loss, ps, ncycle(dtrain, 10), opt)source diff --git a/dev/models/layers/index.html b/dev/models/layers/index.html index 1a91405f..4a8b587b 100644 --- a/dev/models/layers/index.html +++ b/dev/models/layers/index.html @@ -11,41 +11,41 @@ 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

Convolution and Pooling Layers

These layers are used to build convolutional neural networks (CNNs).

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

Convolution and Pooling Layers

These layers are used to build convolutional neural networks (CNNs).

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.

Example: Applying Conv layer to a 1-channel input using a 2x2 window size, giving us a 16-channel output. Output is activated with ReLU.

size = (2,2)
 in = 1
 out = 16
-Conv((2, 2), 1=>16, relu)

Data should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.

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
Flux.DepthwiseConvType.
DepthwiseConv(size, in=>out)
-DepthwiseConv(size, in=>out, relu)

Depthwise convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively. Note that out must be an integer multiple of in.

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.ConvTransposeType.
ConvTranspose(size, in=>out)
-ConvTranspose(size, in=>out, relu)

Standard convolutional transpose 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.CrossCorType.
CrossCor(size, in=>out)
+Conv((2, 2), 1=>16, relu)

Data should be stored in WHCN order (width, height, # channels, batch size). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.

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
Flux.DepthwiseConvType.
DepthwiseConv(size, in=>out)
+DepthwiseConv(size, in=>out, relu)

Depthwise convolutional layer. size should be a tuple like (2, 2). in and out specify the number of input and output channels respectively. Note that out must be an integer multiple of in.

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.ConvTransposeType.
ConvTranspose(size, in=>out)
+ConvTranspose(size, in=>out, relu)

Standard convolutional transpose 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.CrossCorType.
CrossCor(size, in=>out)
 CrossCor(size, in=>out, relu)

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

Example: Applying CrossCor layer to a 1-channel input using a 2x2 window size, giving us a 16-channel output. Output is activated with ReLU.

size = (2,2)
 in = 1
 out = 16
-CrossCor((2, 2), 1=>16, relu)

Data should be stored in WHCN order (width, height, # channels, # batches). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.

Takes the keyword arguments pad, stride and dilation.

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)
+CrossCor((2, 2), 1=>16, relu)

Data should be stored in WHCN order (width, height, # channels, # batches). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array.

Takes the keyword arguments pad, stride and dilation.

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

Other General Purpose Layers

These are marginally more obscure than the Basic Layers. But in contrast to the layers described in the other sections are not readily grouped around a particular purpose (e.g. CNNs or RNNs).

Flux.MaxoutType.
Maxout(over)

Maxout is a neural network layer, which has a number of internal layers, which all have the same input, and the maxout returns the elementwise maximium of the internal layers' outputs.

Maxout over linear dense layers satisfies the univeral approximation theorem.

Reference: Ian J. Goodfellow, David Warde-Farley, Mehdi Mirza, Aaron Courville, and Yoshua Bengio.

  1. Maxout networks.

In Proceedings of the 30th International Conference on International Conference on Machine Learning - Volume 28 (ICML'13), Sanjoy Dasgupta and David McAllester (Eds.), Vol. 28. JMLR.org III-1319-III-1327. https://arxiv.org/pdf/1302.4389.pdf

source
Flux.SkipConnectionType.
SkipConnection(layers, connection)

Creates a Skip Connection, of a layer or Chain of consecutive layers plus a shortcut connection. The connection function will combine the result of the layers with the original input, to give the final output.

The simplest 'ResNet'-type connection is just SkipConnection(layer, +), and requires the output of the layers to be the same shape as the input. Here is a more complicated example:

m = Conv((3,3), 4=>7, pad=(1,1))
+rnn.state # 60
source

Other General Purpose Layers

These are marginally more obscure than the Basic Layers. But in contrast to the layers described in the other sections are not readily grouped around a particular purpose (e.g. CNNs or RNNs).

Flux.MaxoutType.
Maxout(over)

Maxout is a neural network layer, which has a number of internal layers, which all have the same input, and the maxout returns the elementwise maximium of the internal layers' outputs.

Maxout over linear dense layers satisfies the univeral approximation theorem.

Reference: Ian J. Goodfellow, David Warde-Farley, Mehdi Mirza, Aaron Courville, and Yoshua Bengio.

  1. Maxout networks.

In Proceedings of the 30th International Conference on International Conference on Machine Learning - Volume 28 (ICML'13), Sanjoy Dasgupta and David McAllester (Eds.), Vol. 28. JMLR.org III-1319-III-1327. https://arxiv.org/pdf/1302.4389.pdf

source
Flux.SkipConnectionType.
SkipConnection(layers, connection)

Creates a Skip Connection, of a layer or Chain of consecutive layers plus a shortcut connection. The connection function will combine the result of the layers with the original input, to give the final output.

The simplest 'ResNet'-type connection is just SkipConnection(layer, +), and requires the output of the layers to be the same shape as the input. Here is a more complicated example:

m = Conv((3,3), 4=>7, pad=(1,1))
 x = ones(5,5,4,10);
 size(m(x)) == (5, 5, 7, 10)
 
 sm = SkipConnection(m, (mx, x) -> cat(mx, x, dims=3))
-size(sm(x)) == (5, 5, 11, 10)
source

Normalisation & Regularisation

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

Flux.BatchNormType.
BatchNorm(channels::Integer, σ = identity;
+size(sm(x)) == (5, 5, 11, 10)
source

Normalisation & Regularisation

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

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

Use testmode! during inference.

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, dims = :)

A Dropout layer. In the forward pass, applies the dropout function on the input.

Does nothing to the input once testmode! is false.

source
Flux.dropoutFunction.
dropout(p, dims = :)

Dropout function. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). The dims argument is to specify the unbroadcasted dimensions, i.e. dims=1 does dropout along columns and dims=2 along rows. This is used as a regularisation, i.e. it reduces overfitting during training.

See also Dropout.

source
Flux.AlphaDropoutType.
AlphaDropout(p)

A dropout layer. It is used in Self-Normalizing Neural Networks. (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf) The AlphaDropout layer ensures that mean and variance of activations remains the same as before.

Does nothing to the input once testmode! is false.

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
Flux.GroupNormType.

Group Normalization. This layer can outperform Batch-Normalization and Instance-Normalization.

GroupNorm(chs::Integer, G::Integer, λ = identity;
+  softmax)
source
Flux.DropoutType.
Dropout(p, dims = :)

A Dropout layer. In the forward pass, applies the dropout function on the input.

Does nothing to the input once testmode! is false.

source
Flux.dropoutFunction.
dropout(p, dims = :)

Dropout function. For each input, either sets that input to 0 (with probability p) or scales it by 1/(1-p). The dims argument is to specify the unbroadcasted dimensions, i.e. dims=1 does dropout along columns and dims=2 along rows. This is used as a regularisation, i.e. it reduces overfitting during training.

See also Dropout.

source
Flux.AlphaDropoutType.
AlphaDropout(p)

A dropout layer. It is used in Self-Normalizing Neural Networks. (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf) The AlphaDropout layer ensures that mean and variance of activations remains the same as before.

Does nothing to the input once testmode! is false.

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
Flux.GroupNormType.

Group Normalization. This layer can outperform Batch-Normalization and Instance-Normalization.

GroupNorm(chs::Integer, G::Integer, λ = identity;
           initβ = (i) -> zeros(Float32, i), initγ = (i) -> ones(Float32, i),
           ϵ = 1f-5, momentum = 0.1f0)

$chs$ is the number of channels, the channel dimension of your input. For an array of N dimensions, the (N-1)th index is the channel dimension.

$G$ is the number of groups along which the statistics would be computed. The number of channels must be an integer multiple of the number of groups.

Use testmode! during inference.

Example:

m = Chain(Conv((3,3), 1=>32, leakyrelu;pad = 1),
-          GroupNorm(32,16)) # 32 channels, 16 groups (G = 16), thus 2 channels per group used

Link : https://arxiv.org/pdf/1803.08494.pdf

source

Testmode

Many normalisation layers behave differently under training and inference (testing). By default, Flux will automatically determine when a layer evaluation is part of training or inference. Still, depending on your use case, it may be helpful to manually specify when these layers should be treated as being trained or not. For this, Flux provides testmode!. When called on a model (e.g. a layer or chain of layers), this function will place the model into the mode specified.

Flux.testmode!Function.
testmode!(m, mode = true)

Set a layer or model's test mode (see below). Using :auto mode will treat any gradient computation as training.

Note: if you manually set a model into test mode, you need to manually place it back into train mode during training phase.

Possible values include:

  • false for training
  • true for testing
  • :auto or nothing for Flux to detect the mode automatically
source
Flux.trainmode!Function.
trainmode!(m, mode = true)

Set a layer of model's train mode (see below). Symmetric to testmode! (i.e. `trainmode!(m, mode) == testmode!(m, !mode)).

Note: if you manually set a model into train mode, you need to manually place it into test mode during testing phase.

Possible values include:

  • true for training
  • false for testing
  • :auto or nothing for Flux to detect the mode automatically
source

Cost Functions

Flux.mseFunction.
mse(ŷ, y)

Return the mean squared error sum((ŷ .- y).^2) / length(y).

source
Flux.crossentropyFunction.
crossentropy(ŷ, y; weight=1)

Return the crossentropy computed as -sum(y .* log.(ŷ) .* weight) / size(y, 2).

See also logitcrossentropy, binarycrossentropy.

source
Flux.logitcrossentropyFunction.
logitcrossentropy(ŷ, y; weight=1)

Return the crossentropy computed after a softmax operation:

-sum(y .* logsoftmax(ŷ) .* weight) / size(y, 2)

See also crossentropy, binarycrossentropy.

source
Flux.binarycrossentropyFunction.
binarycrossentropy(ŷ, y; ϵ=eps(ŷ))

Return -y*log(ŷ + ϵ) - (1-y)*log(1-ŷ + ϵ). The ϵ term provides numerical stability.

Typically, the prediction is given by the output of a sigmoid activation.

source
Flux.logitbinarycrossentropyFunction.
logitbinarycrossentropy(ŷ, y)

logitbinarycrossentropy(ŷ, y) is mathematically equivalent to binarycrossentropy(σ(ŷ), y) but it is more numerically stable.

See also binarycrossentropy, sigmoid, logsigmoid.

source
Flux.kldivergenceFunction.
kldivergence(ŷ, y)

KLDivergence is a measure of how much one probability distribution is different from the other. It is always non-negative and zero only when both the distributions are equal everywhere. KL Divergence.

source
Flux.poissonFunction.
poisson(ŷ, y)

Poisson loss function is a measure of how the predicted distribution diverges from the expected distribution. Poisson Loss.

source
Flux.hingeFunction.
hinge(ŷ, y)

Measures the loss given the prediction and true labels y (containing 1 or -1). Hinge Loss.

source
+ GroupNorm(32,16)) # 32 channels, 16 groups (G = 16), thus 2 channels per group used

Link : https://arxiv.org/pdf/1803.08494.pdf

source

Testmode

Many normalisation layers behave differently under training and inference (testing). By default, Flux will automatically determine when a layer evaluation is part of training or inference. Still, depending on your use case, it may be helpful to manually specify when these layers should be treated as being trained or not. For this, Flux provides testmode!. When called on a model (e.g. a layer or chain of layers), this function will place the model into the mode specified.

Flux.testmode!Function.
testmode!(m, mode = true)

Set a layer or model's test mode (see below). Using :auto mode will treat any gradient computation as training.

Note: if you manually set a model into test mode, you need to manually place it back into train mode during training phase.

Possible values include:

  • false for training
  • true for testing
  • :auto or nothing for Flux to detect the mode automatically
source
Flux.trainmode!Function.
trainmode!(m, mode = true)

Set a layer of model's train mode (see below). Symmetric to testmode! (i.e. `trainmode!(m, mode) == testmode!(m, !mode)).

Note: if you manually set a model into train mode, you need to manually place it into test mode during testing phase.

Possible values include:

  • true for training
  • false for testing
  • :auto or nothing for Flux to detect the mode automatically
source

Cost Functions

Flux.mseFunction.
mse(ŷ, y)

Return the mean squared error sum((ŷ .- y).^2) / length(y).

source
Flux.crossentropyFunction.
crossentropy(ŷ, y; weight=1)

Return the crossentropy computed as -sum(y .* log.(ŷ) .* weight) / size(y, 2).

See also logitcrossentropy, binarycrossentropy.

source
Flux.logitcrossentropyFunction.
logitcrossentropy(ŷ, y; weight=1)

Return the crossentropy computed after a softmax operation:

-sum(y .* logsoftmax(ŷ) .* weight) / size(y, 2)

See also crossentropy, binarycrossentropy.

source
Flux.binarycrossentropyFunction.
binarycrossentropy(ŷ, y; ϵ=eps(ŷ))

Return -y*log(ŷ + ϵ) - (1-y)*log(1-ŷ + ϵ). The ϵ term provides numerical stability.

Typically, the prediction is given by the output of a sigmoid activation.

source
Flux.logitbinarycrossentropyFunction.
logitbinarycrossentropy(ŷ, y)

logitbinarycrossentropy(ŷ, y) is mathematically equivalent to binarycrossentropy(σ(ŷ), y) but it is more numerically stable.

See also binarycrossentropy, sigmoid, logsigmoid.

source
Flux.kldivergenceFunction.
kldivergence(ŷ, y)

KLDivergence is a measure of how much one probability distribution is different from the other. It is always non-negative and zero only when both the distributions are equal everywhere. KL Divergence.

source
Flux.poissonFunction.
poisson(ŷ, y)

Poisson loss function is a measure of how the predicted distribution diverges from the expected distribution. Poisson Loss.

source
Flux.hingeFunction.
hinge(ŷ, y)

Measures the loss given the prediction and true labels y (containing 1 or -1). Hinge Loss.

source
diff --git a/dev/training/optimisers/index.html b/dev/training/optimisers/index.html index 9affe30a..1649d9fd 100644 --- a/dev/training/optimisers/index.html +++ b/dev/training/optimisers/index.html @@ -28,7 +28,7 @@ end

Running this will alter the parameters W and

An optimiser update! accepts a parameter and a gradient, and updates the parameter according to the chosen rule. We can also pass opt to our training loop, which will update all parameters of the model in a loop. However, we can now easily replace Descent with a more advanced optimiser such as ADAM.

Optimiser Reference

All optimisers return an object that, when passed to train!, will update the parameters passed to it.

Flux.Optimise.update!Function.
update!(opt, p, g)
-update!(opt, ps::Params, gs)

Perform an update step of the parameters ps (or the single parameter p) according to optimizer opt and the gradients gs (the gradient g).

As a result, the parameters are mutated and the optimizer's internal state may change.

update!(x, x̄)

Update the array x according to x .-= x̄.

source
Flux.Optimise.DescentType.
Descent(η)

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

Parameters

  • Learning Rate (η): The amount by which the gradients are discounted before updating the weights. Defaults to 0.1.

Example

opt = Descent() # uses default η (0.1)
+update!(opt, ps::Params, gs)

Perform an update step of the parameters ps (or the single parameter p) according to optimizer opt and the gradients gs (the gradient g).

As a result, the parameters are mutated and the optimizer's internal state may change.

update!(x, x̄)

Update the array x according to x .-= x̄.

source
Flux.Optimise.DescentType.
Descent(η)

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

Parameters

  • Learning Rate (η): The amount by which the gradients are discounted before updating the weights. Defaults to 0.1.

Example

opt = Descent() # uses default η (0.1)
 
 opt = Descent(0.3) # use provided η
 
@@ -38,23 +38,23 @@ gs = gradient(ps) do
   loss(x, y)
 end
 
-Flux.Optimise.update!(opt, ps, gs)
source
Flux.Optimise.MomentumType.
Momentum(η, ρ)

Gradient descent with learning rate η and momentum ρ.

Parameters

  • Learning Rate (η): Amount by which gradients are discounted before updating the weights. Defaults to 0.01.
  • Momentum (ρ): Parameter that accelerates descent in the relevant direction and dampens oscillations. Defaults to 0.9.

Examples

opt = Momentum() # uses defaults of η = 0.01 and ρ = 0.9
+Flux.Optimise.update!(opt, ps, gs)
source
Flux.Optimise.MomentumType.
Momentum(η, ρ)

Gradient descent with learning rate η and momentum ρ.

Parameters

  • Learning Rate (η): Amount by which gradients are discounted before updating the weights. Defaults to 0.01.
  • Momentum (ρ): Parameter that accelerates descent in the relevant direction and dampens oscillations. Defaults to 0.9.

Examples

opt = Momentum() # uses defaults of η = 0.01 and ρ = 0.9
 
-opt = Momentum(0.01, 0.99)
source
Flux.Optimise.NesterovType.
Nesterov(η, ρ)

Gradient descent with learning rate η and Nesterov momentum ρ.

Parameters

  • Learning Rate (η): Amount by which the gradients are dicsounted berfore updating the weights. Defaults to 0.001.
  • Nesterov Momentum (ρ): Parameters controlling the amount of nesterov momentum to be applied. Defaults to 0.9.

Examples

opt = Nesterov() # uses defaults η = 0.001 and ρ = 0.9
+opt = Momentum(0.01, 0.99)
source
Flux.Optimise.NesterovType.
Nesterov(η, ρ)

Gradient descent with learning rate η and Nesterov momentum ρ.

Parameters

  • Learning Rate (η): Amount by which the gradients are dicsounted berfore updating the weights. Defaults to 0.001.
  • Nesterov Momentum (ρ): Parameters controlling the amount of nesterov momentum to be applied. Defaults to 0.9.

Examples

opt = Nesterov() # uses defaults η = 0.001 and ρ = 0.9
 
-opt = Nesterov(0.003, 0.95)
source
Flux.Optimise.RMSPropType.
RMSProp(η, ρ)

Implements the RMSProp algortihm. Often a good choice for recurrent networks. Parameters other than learning rate generally don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Rho (ρ): Defaults to 0.9.

Examples

opt = RMSProp() # uses default η = 0.001 and ρ = 0.9
+opt = Nesterov(0.003, 0.95)
source
Flux.Optimise.RMSPropType.
RMSProp(η, ρ)

Implements the RMSProp algortihm. Often a good choice for recurrent networks. Parameters other than learning rate generally don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Rho (ρ): Defaults to 0.9.

Examples

opt = RMSProp() # uses default η = 0.001 and ρ = 0.9
 
-opt = RMSProp(0.002, 0.95)

References

RMSProp

source
Flux.Optimise.ADAMType.
ADAM(η, β::Tuple)

Implements the ADAM optimiser.

Paramters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = ADAM() # uses the default η = 0.001 and β = (0.9, 0.999)
+opt = RMSProp(0.002, 0.95)

References

RMSProp

source
Flux.Optimise.ADAMType.
ADAM(η, β::Tuple)

Implements the ADAM optimiser.

Paramters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = ADAM() # uses the default η = 0.001 and β = (0.9, 0.999)
 
-opt = ADAM(0.001, (0.9, 0.8))

References

ADAM optimiser.

source
Flux.Optimise.AdaMaxType.
AdaMax(η, β::Tuple)

Variant of ADAM based on ∞-norm.

Parameters

  • Learning Rate (η): Defaults to 0.001
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = AdaMax() # uses default η and β
+opt = ADAM(0.001, (0.9, 0.8))

References

ADAM optimiser.

source
Flux.Optimise.AdaMaxType.
AdaMax(η, β::Tuple)

Variant of ADAM based on ∞-norm.

Parameters

  • Learning Rate (η): Defaults to 0.001
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = AdaMax() # uses default η and β
 
-opt = AdaMax(0.001, (0.9, 0.995))

References

AdaMax optimiser.

source
Flux.Optimise.ADAGradType.
ADAGrad(η)

Implements AdaGrad. It has parameter specific learning rates based on how frequently it is updated.

Parameters

  • Learning Rate (η): Defaults to 0.1

Examples

opt = ADAGrad() # uses default η = 0.1
+opt = AdaMax(0.001, (0.9, 0.995))

References

AdaMax optimiser.

source
Flux.Optimise.ADAGradType.
ADAGrad(η)

Implements AdaGrad. It has parameter specific learning rates based on how frequently it is updated.

Parameters

  • Learning Rate (η): Defaults to 0.1

Examples

opt = ADAGrad() # uses default η = 0.1
 
-opt = ADAGrad(0.001)

References

ADAGrad optimiser. Parameters don't need tuning.

source
Flux.Optimise.ADADeltaType.
ADADelta(ρ)

Version of ADAGrad that adapts learning rate based on a window of past gradient updates. Parameters don't need tuning.

Parameters

  • Rho (ρ): Factor by which gradient is decayed at each time step. Defaults to 0.9.

Examples

opt = ADADelta() # uses default ρ = 0.9
-opt = ADADelta(0.89)

References

ADADelta optimiser.

source
Flux.Optimise.AMSGradType.
AMSGrad(η, β::Tuple)

Implements AMSGrad version of the ADAM optimiser. Parameters don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = AMSGrad() # uses default η and β
-opt = AMSGrad(0.001, (0.89, 0.995))

References

AMSGrad optimiser.

source
Flux.Optimise.NADAMType.
NADAM(η, β::Tuple)

Nesterov variant of ADAM. Parameters don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = NADAM() # uses default η and β
-opt = NADAM(0.002, (0.89, 0.995))

References

NADAM optimiser.

source
Flux.Optimise.ADAMWFunction.
ADAMW(η, β::Tuple, decay)

Variant of ADAM defined by fixing weight decay regularization.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).
  • decay: Decay applied to weights during optimisation. Defaults to 0.

Examples

opt = ADAMW() # uses default η, β and decay
-opt = ADAMW(0.001, (0.89, 0.995), 0.1)

References

ADAMW

source

Optimiser Interface

Flux's optimisers are built around a struct that holds all the optimiser parameters along with a definition of how to apply the update rule associated with it. We do this via the apply! function which takes the optimiser as the first argument followed by the parameter and its corresponding gradient.

In this manner Flux also allows one to create custom optimisers to be used seamlessly. Let's work this with a simple example.

mutable struct Momentum
+opt = ADAGrad(0.001)

References

ADAGrad optimiser. Parameters don't need tuning.

source
Flux.Optimise.ADADeltaType.
ADADelta(ρ)

Version of ADAGrad that adapts learning rate based on a window of past gradient updates. Parameters don't need tuning.

Parameters

  • Rho (ρ): Factor by which gradient is decayed at each time step. Defaults to 0.9.

Examples

opt = ADADelta() # uses default ρ = 0.9
+opt = ADADelta(0.89)

References

ADADelta optimiser.

source
Flux.Optimise.AMSGradType.
AMSGrad(η, β::Tuple)

Implements AMSGrad version of the ADAM optimiser. Parameters don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = AMSGrad() # uses default η and β
+opt = AMSGrad(0.001, (0.89, 0.995))

References

AMSGrad optimiser.

source
Flux.Optimise.NADAMType.
NADAM(η, β::Tuple)

Nesterov variant of ADAM. Parameters don't need tuning.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).

Examples

opt = NADAM() # uses default η and β
+opt = NADAM(0.002, (0.89, 0.995))

References

NADAM optimiser.

source
Flux.Optimise.ADAMWFunction.
ADAMW(η, β::Tuple, decay)

Variant of ADAM defined by fixing weight decay regularization.

Parameters

  • Learning Rate (η): Defaults to 0.001.
  • Beta (β::Tuple): The first element refers to β1 and the second to β2. Defaults to (0.9, 0.999).
  • decay: Decay applied to weights during optimisation. Defaults to 0.

Examples

opt = ADAMW() # uses default η, β and decay
+opt = ADAMW(0.001, (0.89, 0.995), 0.1)

References

ADAMW

source

Optimiser Interface

Flux's optimisers are built around a struct that holds all the optimiser parameters along with a definition of how to apply the update rule associated with it. We do this via the apply! function which takes the optimiser as the first argument followed by the parameter and its corresponding gradient.

In this manner Flux also allows one to create custom optimisers to be used seamlessly. Let's work this with a simple example.

mutable struct Momentum
   eta
   rho
   velocity
@@ -81,4 +81,4 @@ for t = 1:10^5
 end
 
 loss(rand(10)) # around 0.9

In this manner it is possible to compose optimisers for some added flexibility.

Decays

Similar to optimisers, Flux also defines some simple decays that can be used in conjunction with other optimisers, or standalone.

Flux.Optimise.ExpDecayType.
ExpDecay(eta, decay, decay_step, clip)

Discount the learning rate eta by a multiplicative factor decay every decay_step till a minimum of clip.

Parameters

  • Learning Rate (eta): Defaults to 0.001.
  • decay: Factor by which the learning rate is discounted. Defaults to 0.1.
  • decay_step: Schedules decay operations by setting number of steps between two decay operations. Defaults to 1000.
  • clip: Minimum value of learning rate. Defaults to 1e-4.

Example

To apply exponential decay to an optimiser:

Optimiser(ExpDecay(..), Opt(..))
-opt = Optimiser(ExpDecay(), ADAM())
source
Flux.Optimise.InvDecayType.
InvDecay(γ)

Applies inverse time decay to an optimiser, i.e., the effective step size at iteration n is eta / (1 + γ * n) where eta is the initial step size. The wrapped optimiser's step size is not modified.

Parameters

  • gamma (γ): Defaults to 0.001

Example

Optimiser(InvDecay(..), Opt(..))
source
Flux.Optimise.WeightDecayType.
WeightDecay(wd)

Decays the weight by wd

Parameters

  • weight decay (wd): 0
source
+opt = Optimiser(ExpDecay(), ADAM())source
Flux.Optimise.InvDecayType.
InvDecay(γ)

Applies inverse time decay to an optimiser, i.e., the effective step size at iteration n is eta / (1 + γ * n) where eta is the initial step size. The wrapped optimiser's step size is not modified.

Parameters

  • gamma (γ): Defaults to 0.001

Example

Optimiser(InvDecay(..), Opt(..))
source
Flux.Optimise.WeightDecayType.
WeightDecay(wd)

Decays the weight by wd

Parameters

  • weight decay (wd): 0
source
diff --git a/dev/training/training/index.html b/dev/training/training/index.html index cfff4b2d..876f7a05 100644 --- a/dev/training/training/index.html +++ b/dev/training/training/index.html @@ -6,7 +6,7 @@ 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'); -

Training

Training

To actually train a model we need four things:

With these we can call train!:

Flux.Optimise.train!Function.
train!(loss, params, data, opt; cb)

For each datapoint d in data computes the gradient of loss(d...) through backpropagation and calls the optimizer opt.

In case datapoints d are of numeric array type, assumes no splatting is needed and computes the gradient of loss(d).

Takes a callback as keyword argument cb. For example, this will print "training" every 10 seconds:

train!(loss, params, data, opt, cb = throttle(() -> println("training"), 10))

The callback can call Flux.stop() to interrupt the training loop.

Multiple optimisers and callbacks can be passed to opt and cb as arrays.

source

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(
+

Training

Training

To actually train a model we need four things:

  • A objective function, that evaluates how well a model is doing given some input data.
  • The trainable parameters of the model.
  • 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 train!:

Flux.Optimise.train!Function.
train!(loss, params, data, opt; cb)

For each datapoint d in data computes the gradient of loss(d...) through backpropagation and calls the optimizer opt.

In case datapoints d are of numeric array type, assumes no splatting is needed and computes the gradient of loss(d).

Takes a callback as keyword argument cb. For example, this will print "training" every 10 seconds:

train!(loss, params, data, opt, cb = throttle(() -> println("training"), 10))

The callback can call Flux.stop() to interrupt the training loop.

Multiple optimisers and callbacks can be passed to opt and cb as arrays.

source

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)