np.random.randint causes ValueError: low >= high [closed]

I’m working on CapsNet from here , which is implemented on the MNIST dataset with 10 digits, but I’ve changed the code to work with a dataset with three classes. Model training and testing work fine, but the manipulate latent function causes an error:

  def manipulate_latent(model, data, args):
        x_test, y_test = data
        index = np.argmax(y_test, 1) == args.digit
        print(index)
        number = np.random.randint(low=0, high=sum(index) - 1)
        x, y = x_test[index][number], y_test[index][number]
        x, y = np.expand_dims(x, 0), np.expand_dims(y, 0)
        noise = np.zeros([1, 3, 16])
        x_recons = []
        for dim in range(16):
            for r in [-0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25]:
                tmp = np.copy(noise)
                tmp[:,:,dim] = r
                x_recon = model.predict([x, y, tmp])
                x_recons.append(x_recon)
        x_recons = np.concatenate(x_recons)
        img = combine_images(x_recons, height=16)
        image = img*255
        Image.fromarray(image.astype(np.uint8)).save(args.save_dir + '/manipulate-%d.png' % args.digit)

The output is:

number = np.random.randint(low=0, high=sum(index) – 1) ValueError: low >= high

Function call:

model, eval_model, manipulate_model = CapsNet(input_shape=x_train.shape[1:],
                                                  n_class=len(np.unique(np.argmax(y_train, 1))),
                                                  routings=args.routings)
manipulate_latent(manipulate_model, (x_test, y_test), args)

Answer

This is because you’re using sum() instead of len().

x = [False, False, False]
print(sum(x))
print(len(x))

Output

0
2

Notice, that sum() of an array of False is equal to 0. While the len() is the size of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *