简体   繁体   中英

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?

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]])

This line:

shifted_image.reshape([-1])

Is simply calling the reshape method with a list as parameter, and the list happens to contain a single element, the number -1 . This has the effect of reshaping the numpy array. From the docs:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions

The method reshape takes a list of integers as its parameter, and in this case the element of the list is -1.

The -1 specifically is affecting resizing, which I'm sure you could find in the numpy documentation.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM