def make_weights_for_balanced_classes(images, nclasses):
    """
    Generates weights to get balanced classes during training. To be used with weighted random samplers.

    :param images: list of training images in training set.
    :param nclasses: number of classes on training set.
    :return: list of weights for each training image.
    """
    count = [0] * nclasses
    for item in images:
        count[item[1]] += 1
    weight_per_class = [0.] * nclasses
    N = float(sum(count))
    for i in range(nclasses):
        weight_per_class[i] = N / float(count[i])
    weight = [0] * len(images)
    for idx, val in enumerate(images):
        weight[idx] = weight_per_class[val[1]]
    return weight