Numpy resize在使用-1语法时给出了意外的数组大小

2024-03-29 08:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解numpy.resizenumpy.reshape之间的区别。我知道resize将返回一个新数组,reshape将维护相同的底层数据,并且只调整大小(我假设它通过改变步长来实现这一点)。但是,对于这两个函数,我希望能够使用-1语法来指定轴的大小。然而,这似乎只适用于reshape。例如,尝试将此一维形状数组(444,)重塑为形状数组(4, 111)会产生两种不同的结果,具体取决于您是使用resize还是reshape

import numpy as np

test = np.arange(0, 444)
print(test.shape)
print(np.resize(test, (4, -1)).shape)
print(np.reshape(test, (4, -1)).shape)

印刷品

(444,)
(4, 110)
(4, 111)

我假设我遗漏了resize函数的某些内容,但我希望它要么输出与(444,)兼容的形状,要么抛出一个错误。你知道吗


Tags: 数据函数testnumpynp语法数组形状
2条回答

浏览^{}的源代码,您可以看到发生了什么,而且-1从来没有打算作为输入:

def resize(a, new_shape):
    if isinstance(new_shape, (int, nt.integer)):
        new_shape = (new_shape,)
    a = ravel(a)
    Na = len(a)   # Na = 444
    total_size = um.multiply.reduce(new_shape)   # total_size = 4 * -1 = -4 (?!?)
    if Na == 0 or total_size == 0:
        return mu.zeros(new_shape, a.dtype)

    n_copies = int(total_size / Na)    # n_copies = 0, luckily
    extra = total_size % Na            # -4 % 444 = 440 (this is where the 110 comes from)

    if extra != 0:  # True
        n_copies = n_copies + 1        # n_copies = 1 
        extra = Na - extra             # extra = 444 - 440 = 4

    a = concatenate((a,) * n_copies)   # a stays same
    if extra > 0:                      # True
        a = a[:-extra]                 # a = a[:-4]
    return reshape(a, new_shape)       # this is .reshape(4, -1) which now gives (4, 110)

np.resize-1的行为没有文档记录。但可以从Python代码或以下示例中推断:

In [312]: np.resize(np.arange(12),(1,-1))                                       
Out[312]: array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]])
In [313]: np.resize(np.arange(12),(2,-1))                                       
Out[313]: 
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
In [314]: np.resize(np.arange(12),(3,-1))                                       
Out[314]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [315]: np.resize(np.arange(12),(4,-1))                                       
Out[315]: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
# (5,-1) error
In [317]: np.resize(np.arange(12),(6,-1))                                       
Out[317]: 
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5]])

所以一般来说

a = np.arange(n)
np.resize(a, (m,-1))
np.reshape(a[:(n-m)], (m,-1))

也就是说,它通过m元素剪辑输入,并尝试reshape。不是很有用吧?你知道吗

在你的情况下test[:-4].reshape(4,-1)。你知道吗

相关问题 更多 >