简体   繁体   English

关于 -1 的重要性的一般问题

[英]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.我正在处理机器学习中的一个问题,我看到 [-1] 在代码的不同位置经常出现,但我似乎无法理解它的重要性。

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?最后一行的 -1 有什么意义?

In numpy arrays, reshape Allows you to "infer" one of the dimensions when trying to reshape an array. 在numpy数组中, reshape允许您在尝试整形数组时“推断”其中一个尺寸。

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 . 只需使用列表作为参数调用reshape方法,该列表恰好包含单个元素,数字-1 This has the effect of reshaping the numpy array. 这具有重塑numpy数组的效果。 From the docs: 从文档:

One shape dimension can be -1. 一个形状尺寸可以为-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. reshape方法将整数列表作为其参数,在这种情况下,列表的元素为-1。

The -1 specifically is affecting resizing, which I'm sure you could find in the numpy documentation. -1特别影响大小调整,我确定您可以在numpy文档中找到。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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