All topics

Deep learning interview questions

40 questions with answers. 391 open jobs in India ask for Deep learning.

  1. What kind of problems neural nets can solve?Basic

    Neural nets are good at solving non-linear problems. Some good examples are problems that are relatively easy for humans (because of experience, intuition, understanding, etc), but difficult for traditional regression models: speech recognition, handwriting recognition, image identification, etc.

    From Data Science Interviews (CC BY 4.0)

  2. How does a usual fully-connected feed-forward neural network work?Intermediate

    In a usual fully-connected feed-forward network, each neuron receives input from every element of the previous layer and thus the receptive field of a neuron is the entire previous layer. They are usually used to represent feature vectors for input data in classification problems but can be expensive to train because of the number of computations involved.

    From Data Science Interviews (CC BY 4.0)

  3. Why do we need activation functions?Basic

    The main idea of using neural networks is to learn complex nonlinear functions. If we are not using an activation function in between different layers of a neural network, we are just stacking up multiple linear layers one on top of another and this leads to learning a linear function. The Nonlinearity comes only with the activation function, this is the reason we need activation functions.

    From Data Science Interviews (CC BY 4.0)

  4. What are the problems with sigmoid as an activation function?Intermediate

    The derivative of the sigmoid function for large positive or negative numbers is almost zero. From this comes the problem of vanishing gradient — during the backpropagation our net will not learn (or will learn drastically slow). One possible way to solve this problem is to use ReLU activation function.

    From Data Science Interviews (CC BY 4.0)

  5. What is ReLU? How is it better than sigmoid or tanh?Intermediate

    ReLU is an abbreviation for Rectified Linear Unit. It is an activation function which has the value 0 for all negative values and the value f(x) = x for all positive values. The ReLU has a simple activation function which makes it fast to compute and while the sigmoid and tanh activation functions saturate at higher values, the ReLU has a potentially infinite activation, which addresses the problem of vanishing gradients.

    From Data Science Interviews (CC BY 4.0)

  6. How we can initialize the weights of a neural network?Intermediate

    Proper initialization of weight matrix in neural network is very necessary. Simply we can say there are two ways for initializations.

    1. Initializing weights with zeroes. Setting weights to zero makes your network no better than a linear model. It is important to note that setting biases to 0 will not create any troubles as non zero weights take care of breaking the symmetry and even if bias is 0, the values in every neuron are still different.
    2. Initializing weights randomly. Assigning random values to weights is better than just 0 assignment.
    • a) If weights are initialized with very high values the term np.dot(W,X)+b becomes significantly higher and if an activation function like sigmoid() is applied, the function maps its value near to 1 where the slope of gradient changes slowly and learning takes a lot of time.
    • b) If weights are initialized with low values it gets mapped to 0, where the case is the same as above. This problem is often referred to as the vanishing gradient.

    From Data Science Interviews (CC BY 4.0)

  7. What if we set all the weights of a neural network to 0?Intermediate

    If all the weights of a neural network are set to zero, the output of each connection is same (W*x = 0). This means the gradients which are backpropagated to each connection in a layer is same. This means all the connections/weights learn the same thing, and the model never converges.

    From Data Science Interviews (CC BY 4.0)

  8. What regularization techniques for neural nets do you know?Intermediate
    • L1 Regularization - Defined as the sum of absolute values of the individual parameters. The L1 penalty causes a subset of the weights to become zero, suggesting that the corresponding features may safely be discarded.
    • L2 Regularization - Defined as the sum of square of individual parameters. Often supported by regularization hyperparameter alpha. It results in weight decay.
    • Data Augmentation - This requires some fake data to be created as a part of training set.
    • Drop Out : This is most effective regularization technique for neural nets. Few random nodes in each layer is deactivated in forward pass. This allows the algorithm to train on different set of nodes in each iterations.

    From Data Science Interviews (CC BY 4.0)

  9. What is dropout? Why is it useful? How does it work?Intermediate

    Dropout is a technique that at each training step turns off each neuron with a certain probability of p. This way at each iteration we train only 1-p of neurons, which forces the network not to rely only on the subset of neurons for feature representation. This leads to regularizing effects that are controlled by the hyperparameter p.

    From Data Science Interviews (CC BY 4.0)

  10. What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

    If you like ascii art:

    • "VALID" = without padding:

         inputs:         1  2  3  4  5  6  7  8  9  10 11 (12 13)
                        |________________|                dropped
                                       |_________________|
      
    • "SAME" = with zero padding:

                     pad|                                      |pad
         inputs:      0 |1  2  3  4  5  6  7  8  9  10 11 12 13|0  0
                     |________________|
                                    |_________________|
                                                   |________________|
      

    In this example:

    • Input width = 13
    • Filter width = 6
    • Stride = 5

    Notes:

    • "VALID" only ever drops the right-most columns (or bottom-most rows).
    • "SAME" tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom).

    Edit:

    About the name:

    • With "SAME" padding, if you use a stride of 1, the layer's outputs will have the same spatial dimensions as its inputs.
    • With "VALID" padding, there's no "made-up" padding inputs. The layer only uses valid input data.

    From Stack Overflow: asked by karl_TUM, answered by MiniQuark (CC BY-SA 4.0)

  11. Understanding Keras Long Short Term Memories (LSTMs)

    First of all, you choose great tutorials(1,2) to start.

    What Time-step means: Time-steps==3 in X.shape (Describing data shape) means there are three pink boxes. Since in Keras each step requires an input, therefore the number of the green boxes should usually equal to the number of red boxes. Unless you hack the structure.

    many to many vs. many to one: In keras, there is a return_sequences parameter when your initializing LSTM or GRU or SimpleRNN. When return_sequences is False (by default), then it is many to one as shown in the picture. Its return shape is (batch_size, hidden_unit_length), which represent the last state. When return_sequences is True, then it is many to many. Its return shape is (batch_size, time_step, hidden_unit_length)

    Does the features argument become relevant: Feature argument means "How big is your red box" or what is the input dimension each step. If you want to predict from, say, 8 kinds of market information, then you can generate your data with feature==8.

    Stateful: You can look up the source code. When initializing the state, if stateful==True, then the state from last training will be used as the initial state, otherwise it will generate a new state. I haven't turn on stateful yet. However, I disagree with that the batch_size can only be 1 when stateful==True.

    Currently, you generate your data with collected data. Image your stock information is coming as stream, rather than waiting for a day to collect all sequential, you would like to generate input data online while training/predicting with network. If you have 400 stocks sharing a same network, then you can set batch_size==400.

    From Stack Overflow: asked by sachinruk, answered by Van (CC BY-SA 3.0)

  12. Why do we need to call zero_grad() in PyTorch?

    In PyTorch, for every mini-batch during the training phase, we typically want to explicitly set the gradients to zero before starting to do backpropagation (i.e., updating the Weights and biases) because PyTorch accumulates the gradients on subsequent backward passes. This accumulating behavior is convenient while training RNNs or when we want to compute the gradient of the loss summed over multiple mini-batches. So, the default action has been set to accumulate (i.e. sum) the gradients on every loss.backward() call.

    Because of this, when you start your training loop, ideally you should zero out the gradients so that you do the parameter update correctly. Otherwise, the gradient would be a combination of the old gradient, which you have already used to update your model parameters and the newly-computed gradient. It would therefore point in some other direction than the intended direction towards the minimum (or maximum, in case of maximization objectives).

    Here is a simple example:

    import torch
    from torch.autograd import Variable
    import torch.optim as optim
    def linear_model(x, W, b):
        return torch.matmul(x, W) + b
    data, targets = ...
    W = Variable(torch.randn(4, 3), requires_grad=True)
    b = Variable(torch.randn(3), requires_grad=True)
    optimizer = optim.Adam([W, b])
    for sample, target in zip(data, targets):
        # clear out the gradients of all Variables 
        # in this optimizer (i.e. W, b)
        optimizer.zero_grad()
        output = linear_model(sample, W, b)
        loss = (output - target) ** 2
        loss.backward()
        optimizer.step()
    

    Alternatively, if you're doing a vanilla gradient descent, then:

    W = Variable(torch.randn(4, 3), requires_grad=True)
    b = Variable(torch.randn(3), requires_grad=True)
    for sample, target in zip(data, targets):
        # clear out the gradients of Variables 
        # (i.e. W, b)
        W.grad.data.zero_()
        b.grad.data.zero_()
        output = linear_model(sample, W, b)
        loss = (output - target) ** 2
        loss.backward()
        W -= learning_rate * W.grad.data
        b -= learning_rate * b.grad.data
    

    Note:

    • The accumulation (i.e., sum) of gradients happens when .backward() is called on the loss tensor.
    • As of v1.7.0, Pytorch offers the option to reset the gradients to None optimizer.zero_grad(set_to_none=True) instead of filling them with a tensor of zeroes. The docs claim that this setting reduces memory requirements and slightly improves performance, but might be error-prone if not handled carefully.

    From Stack Overflow: asked by user1424739, answered by kmario23 (CC BY-SA 4.0)

  13. Why do we "pack" the sequences in PyTorch?

    I have stumbled upon this problem too and below is what I figured out.

    When training RNN (LSTM or GRU or vanilla-RNN), it is difficult to batch the variable length sequences. For example: if the length of sequences in a size 8 batch is [4,6,8,5,4,3,7,8], you will pad all the sequences and that will result in 8 sequences of length 8. You would end up doing 64 computations (8x8), but you needed to do only 45 computations. Moreover, if you wanted to do something fancy like using a bidirectional-RNN, it would be harder to do batch computations just by padding and you might end up doing more computations than required.

    Instead, PyTorch allows us to pack the sequence, internally packed sequence is a tuple of two lists. One contains the elements of sequences. Elements are interleaved by time steps (see example below) and other contains the size of each sequence the batch size at each step. This is helpful in recovering the actual sequences as well as telling RNN what is the batch size at each time step. This has been pointed by @Aerin. This can be passed to RNN and it will internally optimize the computations.

    I might have been unclear at some points, so let me know and I can add more explanations.

    Here's a code example:

     a = [torch.tensor([1,2,3]), torch.tensor([3,4])]
     b = torch.nn.utils.rnn.pad_sequence(a, batch_first=True)
     >>>>
     tensor([[ 1,  2,  3],
        [ 3,  4,  0]])
     torch.nn.utils.rnn.pack_padded_sequence(b, batch_first=True, lengths=[3,2])
     >>>>PackedSequence(data=tensor([ 1,  3,  2,  4,  3]), batch_sizes=tensor([ 2,  2,  1]))
    

    From Stack Overflow: asked by aerin, answered by Umang Gupta (CC BY-SA 4.0)

  14. What is the role of "Flatten" in Keras?

    If you read the Keras documentation entry for Dense, you will see that this call:

    Dense(16, input_shape=(5,3))
    

    would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

    model = Sequential()
    model.add(Flatten(input_shape=(3, 2)))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(4))
    model.compile(loss='mean_squared_error', optimizer='SGD')
    

    EDIT: As some people struggled to understand - here you have an explaining image:

    From Stack Overflow: asked by Karnivaurus, answered by Marcin Możejko (CC BY-SA 4.0)

  15. What is the use of verbose in Keras while validating the model?

    Check documentation for model.fit here.

    By setting verbose 0, 1 or 2 you just say how do you want to 'see' the training progress for each epoch.

    verbose=0 will show you nothing (silent)

    verbose=1 will show you an animated progress bar like this:

    verbose=2 will just mention the number of epoch like this:

    From Stack Overflow: asked by rakesh, answered by Ankit (CC BY-SA 4.0)

  16. What does tf.nn.embedding_lookup function do?

    embedding_lookup function retrieves rows of the params tensor. The behavior is similar to using indexing with arrays in numpy. E.g.

    matrix = np.random.random([1024, 64])  # 64-dimensional embeddings
    ids = np.array([0, 5, 17, 33])
    print matrix[ids]  # prints a matrix of shape [4, 64] 
    

    params argument can be also a list of tensors in which case the ids will be distributed among the tensors. For example, given a list of 3 tensors [2, 64], the default behavior is that they will represent ids: [0, 3], [1, 4], [2, 5].

    partition_strategy controls the way how the ids are distributed among the list. The partitioning is useful for larger scale problems when the matrix might be too large to keep in one piece.

    From Stack Overflow: asked by Poorya Pzm, answered by Rafał Józefowicz (CC BY-SA 3.0)

  17. What does "unsqueeze" do in Pytorch?

    unsqueeze turns an n.d. tensor into an (n+1).d. one by adding an extra dimension of depth 1. However, since it is ambiguous which axis the new dimension should lie across (i.e. in which direction it should be "unsqueezed"), this needs to be specified by the dim argument.

    e.g. unsqueeze can be applied to a 2d tensor three different ways:

    The resulting unsqueezed tensors have the same information, but the indices used to access them are different.

    From Stack Overflow: asked by user6549804, answered by End genocide - save Gaza (CC BY-SA 4.0)

  18. `stack()` vs `cat()` in PyTorch

    stack

    Concatenates sequence of tensors along a new dimension.

    cat

    Concatenates the given sequence of seq tensors in the given dimension.

    So if A and B are of shape (3, 4):

    • torch.cat([A, B], dim=0) will be of shape (6, 4)
    • torch.stack([A, B], dim=0) will be of shape (2, 3, 4)

    From Stack Overflow: asked by Gulzar, answered by Jatentaki (CC BY-SA 4.0)

  19. What is the role of TimeDistributed layer in Keras?

    In keras - while building a sequential model - usually the second dimension (one after sample dimension) - is related to a time dimension. This means that if for example, your data is 5-dim with (sample, time, width, length, channel) you could apply a convolutional layer using TimeDistributed (which is applicable to 4-dim with (sample, width, length, channel)) along a time dimension (applying the same layer to each time slice) in order to obtain 5-d output.

    The case with Dense is that in keras from version 2.0 Dense is by default applied to only last dimension (e.g. if you apply Dense(10) to input with shape (n, m, o, p) you'll get output with shape (n, m, o, 10)) so in your case Dense and TimeDistributed(Dense) are equivalent.

    From Stack Overflow: asked by Buomsoo Kim, answered by Marcin Możejko (CC BY-SA 3.0)

  20. How does the "number of workers" parameter in PyTorch dataloader actually work?
    1. When num_workers>0, only these workers will retrieve data, main process won't. So when num_workers=2 you have at most 2 workers simultaneously putting data into RAM, not 3.
    2. Well our CPU can usually run like 100 processes without trouble and these worker processes aren't special in anyway, so having more workers than cpu cores is ok. But is it efficient? it depends on how busy your cpu cores are for other tasks, speed of cpu, speed of your hard disk etc. In short, its complicated, so setting workers to number of cores is a good rule of thumb, nothing more.
    3. Nope. Remember DataLoader doesn't just randomly return from what's available in RAM right now, it uses batch_sampler to decide which batch to return next. Each batch is assigned to a worker, and main process will wait until the desired batch is retrieved by assigned worker.

    Lastly to clarify, it isn't DataLoader's job to send anything directly to GPU, you explicitly call cuda() for that.

    EDIT: Don't call cuda() inside Dataset's __getitem__() method, please look at @psarka's comment for the reasoning

    From Stack Overflow: asked by Bassel, answered by Shihab Shahriar Khan (CC BY-SA 4.0)

  21. What's the difference between "hidden" and "output" in PyTorch LSTM?

    I made a diagram. The names follow the PyTorch docs, although I renamed num_layers to w.

    output comprises all the hidden states in the last layer ("last" depth-wise, not time-wise). (h_n, c_n) comprises the hidden states after the last timestep, t = n, so you could potentially feed them into another LSTM.

    The batch dimension is not included.

    From Stack Overflow: asked by N. Virgo, answered by nnnmmm (CC BY-SA 3.0)

  22. Which parameters should be used for early stopping?

    Early stopping is basically stopping the training once your loss starts to increase (or in other words validation accuracy starts to decrease). According to documents it is used as follows;

    keras.callbacks.EarlyStopping(monitor='val_loss',
                                  min_delta=0,
                                  patience=0,
                                  verbose=0, mode='auto')
    

    Values depends on your implementation (problem, batch size etc...) but generally to prevent overfitting I would use;

    1. Monitor the validation loss (need to use cross validation or at least train/test sets) by setting the monitor argument to 'val_loss'.
    2. min_delta is a threshold to whether quantify a loss at some epoch as improvement or not. If the difference of loss is below min_delta, it is quantified as no improvement. Better to leave it as 0 since we're interested in when loss becomes worse.
    3. patience argument represents the number of epochs before stopping once your loss starts to increase (stops improving). This depends on your implementation, if you use very small batches or a large learning rate your loss zig-zag (accuracy will be more noisy) so better set a large patience argument. If you use large batches and a small learning rate your loss will be smoother so you can use a smaller patience argument. Either way I'll leave it as 2 so I would give the model more chance.
    4. verbose decides what to print, leave it at default (0).
    5. mode argument depends on what direction your monitored quantity has (is it supposed to be decreasing or increasing), since we monitor the loss, we can use min. But let's leave keras handle that for us and set that to auto

    So I would use something like this and experiment by plotting the error loss with and without early stopping.

    keras.callbacks.EarlyStopping(monitor='val_loss',
                                  min_delta=0,
                                  patience=2,
                                  verbose=0, mode='auto')
    

    For possible ambiguity on how callbacks work, I'll try to explain more. Once you call fit(... callbacks=[es]) on your model, Keras calls given callback objects predetermined functions. These functions can be called on_train_begin, on_train_end, on_epoch_begin, on_epoch_end and on_batch_begin, on_batch_end. Early stopping callback is called on every epoch end, compares the best monitored value with the current one and stops if conditions are met (how many epochs have past since the observation of the best monitored value and is it more than patience argument, the difference between last value is bigger than min_delta etc..).

    As pointed by @BrentFaust in comments, model's training will continue until either Early Stopping conditions are met or epochs parameter (default=10) in fit() is satisfied. Setting an Early Stopping callback will not make the model to train beyond its epochs parameter. So calling fit() function with a larger epochs value would benefit more from Early Stopping callback.

    From Stack Overflow: asked by AizuddinAzman, answered by umutto (CC BY-SA 3.0)

  23. Keras input explanation: input_shape, units, batch_size, dim, etc

    Units:

    The amount of "neurons", or "cells", or whatever the layer has inside it.

    It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

    • Hidden layer 1: 4 units (4 neurons)
    • Hidden layer 2: 4 units
    • Last layer: 1 unit

    Shapes

    Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

    Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

    The input shape

    What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

    In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

    Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

    Each type of layer requires the input with a certain number of dimensions:

    • Dense layers require inputs as (batch_size, input_size)
      • or (batch_size, optional,...,optional, input_size)
    • 2D convolutional layers need inputs as:
      • if using channels_last: (batch_size, imageside1, imageside2, channels)
      • if using channels_first: (batch_size, channels, imageside1, imageside2)
    • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

    Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

    All the other shapes are calculated automatically based on the units and particularities of each layer.

    Relation between shapes and units - The output shape

    Given the input shape, all other shapes are results of layers calculations.

    The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

    Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

    Let's show what happens with "Dense" layers, which is the type shown in your graph.

    A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

    • Hidden layer 1: 4 units, output shape: (batch_size,4).
    • Hidden layer 2: 4 units, output shape: (batch_size,4).
    • Last layer: 1 unit, output shape: (batch_size,1).

    Weights

    Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

    In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

    In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

    Shapes in Keras

    Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

    Since the input shape is the only one you need to define, Keras will demand it in the first layer.

    Read the rest at the sourceFrom Stack Overflow: asked by scarecrow, answered by Daniel Möller (CC BY-SA 4.0)

  24. How do I save a trained model in PyTorch?

    Found this page on their github repo:

    Recommended approach for saving a model

    There are two main approaches for serializing and restoring a model.

    The first (recommended) saves and loads only the model parameters:

    torch.save(the_model.state_dict(), PATH)
    

    Then later:

    the_model = TheModelClass(*args, **kwargs)
    the_model.load_state_dict(torch.load(PATH))
    

    The second saves and loads the entire model:

    torch.save(the_model, PATH)
    

    Then later:

    the_model = torch.load(PATH)
    

    However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

    See also: Save and Load the Model section from the official PyTorch tutorials.

    From Stack Overflow: asked by Wasi Ahmad, answered by dontloo (CC BY-SA 4.0)

  25. How do I initialize weights in PyTorch?

    Single layer

    To initialize the weights of a single layer, use a function from torch.nn.init. For instance:

    conv1 = torch.nn.Conv2d(...)
    torch.nn.init.xavier_uniform(conv1.weight)
    

    Alternatively, you can modify the parameters by writing to conv1.weight.data (which is a torch.Tensor). Example:

    conv1.weight.data.fill_(0.01)
    

    The same applies for biases:

    conv1.bias.data.fill_(0.01)
    

    nn.Sequential or custom nn.Module

    Pass an initialization function to torch.nn.Module.apply. It will initialize the weights in the entire nn.Module recursively.

    apply(fn): Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init).

    Example:

    def init_weights(m):
        if isinstance(m, nn.Linear):
            torch.nn.init.xavier_uniform(m.weight)
            m.bias.data.fill_(0.01)
    net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
    net.apply(init_weights)
    

    From Stack Overflow: asked by Fábio Perez, answered by Fábio Perez (CC BY-SA 4.0)

  26. Choosing a learning rate
    • Is the learning rate related to the shape of the error gradient, as it dictates the rate of descent?

      • In plain SGD, the answer is no. A global learning rate is used which is indifferent to the error gradient. However, the intuition you are getting at has inspired various modifications of the SGD update rule.
    • If so, how do you use this information to inform your decision about a value?

      • Adagrad is the most widely known of these and scales a global learning rate η on each dimension based on l2 norm of the history of the error gradient gt on each dimension:

      • Adadelta is another such training algorithm which uses both the error gradient history like adagrad and the weight update history and has the advantage of not having to set a learning rate at all.

    • If it's not what sort of values should I choose, and how should I choose them?

      • Setting learning rates for plain SGD in neural nets is usually a process of starting with a sane value such as 0.01 and then doing cross-validation to find an optimal value. Typical values range over a few orders of magnitude from 0.0001 up to 1.
    • It seems like you would want small values to avoid overshooting, but how do you choose one such that you don't get stuck in local minima or take too long to descend? Does it make sense to have a constant learning rate, or should I use some metric to alter its value as I get nearer a minimum in the gradient?

      • Usually, the value that's best is near the highest stable learning rate and learning rate decay/annealing (either linear or exponentially) is used over the course of training. The reason behind this is that early on there is a clear learning signal so aggressive updates encourage exploration while later on the smaller learning rates allow for more delicate exploitation of local error surface.

    From Data Science Stack Exchange: asked by ragingSloth, answered by indico (CC BY-SA 3.0)

  27. When to use (He or Glorot) normal initialization over uniform init? And what are its effects with Batch Normalization?

    The normal vs uniform init seem to be rather unclear in fact.

    If we refer solely on the Glorot's and He's initializations papers, they both use a similar theoritical analysis: they find a good variance for the distribution from which the initial parameters are drawn. This variance is adapted to the activation function used and is derived without explicitly considering the type of the distribution. As such, their theorical conclusions hold for any type of distribution of the determined variance. In fact, in the Glorot paper, a uniform distribution is used whereas in the He paper it is a gaussian one that is chosen. The only "explaination" given for this choice in the He paper is:

    Recent deep CNNs are mostly initialized by random weights drawn from Gaussian distributions

    with a reference to AlexNet paper. It was indeed released a little later than Glorot's initialization but however there is no justificaion in it of the use of a normal distribution.

    In fact, in a discussion on Keras issues tracker, they also seem to be a little confused and basically it could only be a matter of preference... (i.e. hypotetically Bengio would prefer uniform distribution whereas Hinton would prefer normal ones...) One the discussion, there is a small benchmark comparing Glorot initialization using a uniform and a gaussian distribution. In the end, it seems that the uniform wins but it is not really clear.

    In the original ResNet paper, it only says they used a gaussian He init for all the layers, I was not able to find where it is written that they used a uniform He init for the first layer. (maybe you could share a reference to this?)

    As for the use of gaussian init with Batch Normalization, well, with BN the optimization process is less sensitive to initialization thus it is just a convention I would say.

    From Data Science Stack Exchange: asked by Rizky Luthfianto, answered by tlorieul (CC BY-SA 4.0)

  28. Time series prediction using ARIMA vs LSTM

    Statement 1 is correct, statement 2 is correct, but requires elaboration, and statement 3 is incorrect for seasonal ARIMA:

    The following might point you in the right direction but hopefully you'll get a few more answers with more depth in the arena of LSTM.

    You mention that you have tried both algorithms and that you are simply trying to figure out which one is better, which leads me to think you may be having more trouble with the data science process and cross validation than with the specifics of the models.

    Time series in general:

    Time series, in general, are difficult to forecast. If they were easy to forecast then all data scientists would be wealthy, having accurately forecast the value of all of the stocks. The reality is that hedge funds, on average, do not outperform the market and that time series forecasting is typically very poor and applies only to very short durations. The main problems are that there is a lot of noise, there are many hidden influences, models are overly simplistic, influencers do not behave as we think they should, the interplay between linearity and nonlinearity is subtle and confusing, ... ad infinitum.

    ARIMA

    You are incorrect in your assessment that ARIMA requires stationary time series to forecast on. Non-seasonal ARIMA has three input values to help control for smoothing, stationarity, and forecasting ARIMA(p,d,q), where:

    • p is the number of autoregressive terms,
    • d is the number of nonseasonal differences needed for stationarity, and
    • q is the number of lagged forecast errors in the prediction equation.

    By contrast seasonal ARIMA has six input values ARIMA(p,d,q,P,D,Q), where:

    • P is the number of seasonal autoregressive terms,
    • D is the number of seasonal differences, and
    • Q is the number of seasonal moving-average terms.

    Subject to the qualifying statements above, I suggest playing with seasonal ARIMA to get a feel for the intricacies involved in smoothing, de-seasoning, de-trending, de-noiseing, and forecasting.

    LSTM

    I don't know enough about LSTM to add much here. I will add that red flags tend to be raised when someone begins at data science exercise with deep learning. I suggest learning as much as you can using ARIMA and then applying some of your ARIMA expertise to help you learn LSTM. Neural networks can be a very powerful tool, but they:

    • can take a long time to run,
    • often require more data to train than other models, and
    • have lots of input parameters to tune.

    Cross validation and comparing models:

    Time series are fun in that all training data can usually be turned into supervised learning training sets. Once can simply take a time series and roll back time. That is... pick a point in time and pretend that you don't have any additional data, then produce a forecast and see how well you did. You can march through the time series doing this $n$ times in order to get an assessment of the performance of your model and to compare models while taking the necessary precautions to prevent overfitting.

    Hope this helps and good luck!

    From Data Science Stack Exchange: asked by ahajib, answered by AN6U5 (CC BY-SA 3.0)

  29. What is the difference between "equivariant to translation" and "invariant to translation"

    Equivariance and invariance are sometimes used interchangeably in common speech. They have ancient roots in maths and physics. As pointed out by @Xi'an, you can find previous uses (anterior to Convolutional Neural Networks) in the statistical literature, for instance on the notions of the invariant estimator and especially the Pitman estimator.

    However, I would like to mention that it would be better if both terms keep separate meaning, as the prefix "in-" in invariant is privative (meaning "no variance" at all), while "equi-" in equivariant refers to "varying in a similar or equivalent proportion". In other words, one in- does not vary, the other equi- does.

    Let us start from simple image features, and suppose that image $I$ has a unique maximum $m$ at spatial pixel location $(x_m,y_m)$, which is here the main classification feature. In other words: an image and all its translations are "the same". An interesting property of classifiers is their ability to classify in the same manner some distorted versions $I'$ of $I$, for instance translations by all vectors $(u,v)$.

    The maximum value $m'$ of $I'$ is invariant: $m'=m$: the value is the same. While its location will be at $(x'_m,y'_m)=(x_m-u,y_m-v)$, and is equivariant, meaning that is varies "equally" with the distortion.

    The precise formulations given (in mathematical terms) for equivariance depend on the class of objects and transformations one considers: translation, rotation, scale, shear, shift, etc. So I prefer here to focus on the notion that is most often used in practice (I accept the blame from a theoretical stand-point).

    Here, translations by vectors $(u,v)$ of the image (or some more generic actions) can be equipped with a structure of composition, like that of a group $G$ (here the group of translations). One specific $g$ denotes a specific element of the translation group (translational symmetry). A function or feature $f$ is invariant under the group of actions $G$ if for all images in a class, and for any $g$, $$f(g(I)) = f(I)\,.$$

    In other words: if you change the image by action $g$, the values for feature or function $f$ are the same.

    It becomes equivariant if there exists another mathematical structure or action (often a group again) $G'$ that reflects the transformations (from $G$) in $I$ in a meaningful way. In other words, such that for each $g$, you have some (unique?) $g' \in G'$ such that

    $$f(g(I)) = g'(f(I))\,.$$

    In the above example on the group of translations, $g$ and $g'$ are the same (and hence $G'=G$): an integer translation of the image reflects as the exact same translation of the maximum location. This is sometimes refered to as "same-equivariance".

    Another common definition is:

    $$f(g(I)) = g(f(I))\,.$$

    I however used potentially different $G$ and $G'$ because sometimes $f(.)$ and $g(.)$ do not lie in the same domain. This happens for instance in multivariate statistics (see e.g. Equivariance and invariance properties of multivariate quantile and related functions, and the role of standardisation). But here, the uniqueness of the mapping between $g$ and $g'$ allows to get back to the original transformation $g$.

    Often, people use the term invariance because the equivariance concept is unknown, or everybody else uses invariance, and equivariance would seem more pedantic.

    Read the rest at the sourceFrom Data Science Stack Exchange: asked by Aamir , answered by Laurent Duval (CC BY-SA 4.0)

  30. Cross-entropy loss explanation

    The cross entropy formula takes in two distributions, $p(x)$, the true distribution, and $q(x)$, the estimated distribution, defined over the discrete variable $x$ and is given by

    $$H(p,q) = -\sum_{\forall x} p(x) \log(q(x))$$

    For a neural network, the calculation is independent of the following:

    • What kind of layer was used.

    • What kind of activation was used - although many activations will not be compatible with the calculation because their outputs are not interpretable as probabilities (i.e., their outputs are negative, greater than 1, or do not sum to 1). Softmax is often used for multiclass classification because it guarantees a well-behaved probability distribution function.

    For a neural network, you will usually see the equation written in a form where $\mathbf{y}$ is the ground truth vector and $\mathbf{\hat{y}}$ (or some other value taken direct from the last layer output) is the estimate. For a single example, it would look like this:

    $$L = - \mathbf{y} \cdot \log(\mathbf{\hat{y}})$$

    where $\cdot$ is the inner product.

    Your example ground truth $\mathbf{y}$ gives all probability to the first value, and the other values are zero, so we can ignore them, and just use the matching term from your estimates $\mathbf{\hat{y}}$

    $L = -(1\times log(0.1) + 0 \times \log(0.5) + ...)$

    $L = - log(0.1) \approx 2.303$

    An important point from comments

    That means, the loss would be same no matter if the predictions are $[0.1, 0.5, 0.1, 0.1, 0.2]$ or $[0.1, 0.6, 0.1, 0.1, 0.1]$?

    Yes, this is a key feature of multiclass logloss, it rewards/penalises probabilities of correct classes only. The value is independent of how the remaining probability is split between incorrect classes.

    You will often see this equation averaged over all examples as a cost function. It is not always strictly adhered to in descriptions, but usually a loss function is lower level and describes how a single instance or component determines an error value, whilst a cost function is higher level and describes how a complete system is evaluated for optimisation. A cost function based on multiclass log loss for data set of size $N$ might look like this:

    $$J = - \frac{1}{N}\left(\sum_{i=1}^{N} \mathbf{y_i} \cdot \log(\mathbf{\hat{y}_i})\right)$$

    Many implementations will require your ground truth values to be one-hot encoded (with a single true class), because that allows for some extra optimisation. However, in principle the cross entropy loss can be calculated - and optimised - when this is not the case.

    From Data Science Stack Exchange: asked by enterML, answered by Neil Slater (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.