mxnet icon indicating copy to clipboard operation
mxnet copied to clipboard

Strange Validation and Training Losses at epoch change

Open atiyo opened this issue 9 years ago • 3 comments

I struggled to get some mxnet models training to a good accuracy, so I took a closer look at training and validation losses of a toy model. I noticed some strange spikes between epochs, which surprised me.

I expect I'm likely doing something wrong, but I can't see what: I have tried several optimisers, with learning rates spanning several orders of magnitude. It's most plausible that I'm doing something drastically wrong, being new to mxnet.

Graphic below illustrating the phenomenon, and also code to reproduce figure:

adam_loss

import mxnet as mx
import numpy as np

optimizer_choice = 'adam'
learning_rate = 0.01
batch_size = 500

inputs = np.expand_dims(np.random.uniform(low=0., high=2*np.pi, size=10000), axis=1)
labels = np.sin(inputs)

eval_inputs = np.expand_dims(np.random.uniform(low=0., high=2*np.pi, size=10000), axis=1)
eval_labels = np.sin(eval_inputs)

data_iter = mx.io.NDArrayIter(data={'data':inputs}, label={'label':labels}, batch_size=batch_size, shuffle=True)
eval_data_iter = mx.io.NDArrayIter(data={'data':eval_inputs}, label={'label':eval_labels}, batch_size=batch_size, shuffle=True)

data = mx.sym.Variable('data')
label = mx.sym.Variable('label')
fc1 = mx.sym.FullyConnected(data=data, num_hidden=128)
ac1 = mx.sym.Activation(data=fc1, act_type='relu')
fc2 = mx.sym.FullyConnected(data=ac1, num_hidden=64)
ac2 = mx.sym.Activation(data=fc2, act_type='relu')
fc3 = mx.sym.FullyConnected(data=ac2, num_hidden=16)
ac3 = mx.sym.Activation(data=fc3, act_type='relu')
fc4 = mx.sym.FullyConnected(data=ac3, num_hidden=1)
ac4 = mx.sym.Activation(data=fc4, act_type='tanh')
loss = mx.symbol.LinearRegressionOutput(data=ac4, label=label)
net = mx.module.Module(symbol=loss, data_names=['data'], label_names=['label'])

train_error = [] 
eval_error = []
def log_error(period, log):
    def _callback(param):
        if param.nbatch % period == 0:
            name, value = param.eval_metric.get()
            log.append(value)
    return _callback
    
optimizer_params={'learning_rate':learning_rate}
net.fit(data_iter,
      optimizer=optimizer_choice,
      optimizer_params=optimizer_params,
      eval_data=eval_data_iter,
      eval_metric='mse',
      num_epoch=5,
      epoch_end_callback = mx.callback.do_checkpoint('test_net'),
      eval_batch_end_callback = log_error(1,eval_error),
      batch_end_callback = log_error(1,train_error)
      )

train_error = np.array(train_error)
eval_error = np.array(eval_error)
import matplotlib.pyplot as plt
plt.plot(np.arange(train_error.size),train_error, label = 'Training Error')
plt.plot(np.arange(eval_error.size), eval_error, label = 'Validation Error')
plt.legend(loc='upper right')
plt.xlabel('Batch Number')
plt.ylabel('Error')
plt.title('Optimizer: {}. Learning Rate: {}'.format(optimizer_choice,learning_rate))
plt.gca().set_ylim(bottom=0)
plt.show()

Environment info

Operating System: macOS

MXNet version: 0.11.0

Python version and distribution: Python 2.7.13

atiyo avatar Aug 27 '17 20:08 atiyo

It looks like the dip happens for each epoch. Does that indicate sth?

eric-haibin-lin avatar Nov 17 '17 23:11 eric-haibin-lin

Hi,

Because you're tracking the evaluation error after each minibatch rather than after each epoch, the variance you're seeing at the beginning of each epoch is consistent (and also appears to be) due to the fact that you're averaging accuracies over a small number of minibatches. The smaller number of accuracies you're averaging over, the more variance you'll see, and that's why you see more variance at the start of each epoch and then things level out.

Otherwise, there are no indications in the code that anything else is going on, so this seems to be what you're seeing.

In more detail, from metric.py

def update(self, labels, preds):
    """Updates the internal evaluation result.

    Parameters
    ----------
    labels : list of `NDArray`
        The labels of the data.

    preds : list of `NDArray`
        Predicted values.
    """
    labels, preds = check_label_shapes(labels, preds, True)

    for label, pred in zip(labels, preds):
        label = label.asnumpy()
        pred = pred.asnumpy()

        if len(label.shape) == 1:
            label = label.reshape(label.shape[0], 1)
        if len(pred.shape) == 1:
            pred = pred.reshape(pred.shape[0], 1)
A)      self.sum_metric += ((label - pred)**2.0).mean()
B)      self.num_inst += 1 # numpy.prod(label.shape)

Line A computes a running sum of averages and line B keeps track of the number of summands in that running sum (equal to the minibatch number in the epoch).

After each epoch, sum_metric and num_inst are reset, so your averaging starts fresh with only a few number of samples.

In general, the variance of the average of n independent and identically distributed random variables is inversely proportional to the number of random variables (the sample size). Thus as you increase the number of samples, you'll decrease the variance.

https://www.quora.com/How-is-variance-inversely-proportional-to-sample-size https://stats.stackexchange.com/questions/160103/why-does-the-variance-decrease-when-averaging-zero-mean-gaussians

There is a similar "spiking" issue on convergence that I'm including just for interest, but it's unrelated to this phenomenon: https://stats.stackexchange.com/questions/229301/why-does-the-accuracy-of-my-cnn-periodically-spike-down

vishaalkapoor avatar Jul 18 '18 18:07 vishaalkapoor

Still have yet to completely go through @vishaalkapoor's very helpful post above, but I also concluded that it seems that this is not an issue with MXnet a while ago but my incorrect logging of the error. Closing the issue now.

atiyo avatar Jul 18 '18 21:07 atiyo