Search code examples
pythonimagescipyshift

General question about the significance of -1


I'm working on a problem in a machine learning and I see [-1] popping up somewhat frequently in difference places of the code but I can't seem to understand the significance of it.

In this particular example, the goal is to slightly shift all images in the training set.

Here is the code:

from scipy.ndimage.interpolation import shift

def shift_image(image, dx, dy):
    image = image.reshape((28, 28))
    shifted_image = shift(image, [dy, dx], cval=0, mode="constant")
    return shifted_image.reshape([-1])

What is the significance of the -1 in the last line?


Solution

  • In numpy arrays, reshape Allows you to "infer" one of the dimensions when trying to reshape an array.

    import numpy as np
    a = np.arange(4).reshape(2,2)
    #Output:
    array([[0, 1],
           [2, 3]])
    a.reshape([-1])
    #Output:
    array([0, 1, 2, 3])
    

    If you notice, you can also rewrite the first reshape using inference as follows:

    b =np.arange(4).reshape(2,-1)
    #Output:
    array([[0, 1],
           [2, 3]])