def validation(model, val_fn, datagen, mb_size=16):
    """ Validation routine for speech-models
    Params:
        model (keras.model): Constructed keras model
        val_fn (theano.function): A theano function that calculates the cost
            over a validation set
        datagen (DataGenerator)
        mb_size (int): Size of each minibatch
    Returns:
        val_cost (float): Average validation cost over the whole validation set
    """
    avg_cost = 0.0
    i = 0
    for batch in datagen.iterate_validation(mb_size):
        inputs = batch['x']
        labels = batch['y']
        input_lengths = batch['input_lengths']
        label_lengths = batch['label_lengths']
        # Due to convolution, the number of timesteps of the output
        # is different from the input length. Calculate the resulting
        # timesteps
        output_lengths = [model.conv_output_length(l)
                          for l in input_lengths]
        _, ctc_cost = val_fn([inputs, output_lengths, labels,
                              label_lengths, True])
        avg_cost += ctc_cost
        i += 1
    if i == 0:
        return 0.0
    return avg_cost / i