numpy整形实现

ar5n3qh5  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(96)

我主要关注的是this page

第一个,页面看不懂,第一个参数shape

ndarray.reshape(shape, order='C')

字符串
为什么是this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments
也就是说,为什么这个实现允许a.reshape(10, 11)

其次,我想知道GitHub上的实现在哪里?搜索整个句子“Returns an array containing the same data with a new shape”并没有给予我GitHub. My attempt上的正确链接。

谢谢你,谢谢

c9qzyr3d

c9qzyr3d1#

冒着迂腐的风险,这里有一些使用函数和方法版本之间的比较。函数版本接受一个初始对象,它将其解释为数组(或使其成为数组)。方法已经有数组对象(self)。
该函数有一个python签名,该方法是从c编译的,所以可以在其签名上有一些自由(特别是因为它是在py 3和当前标准之前几年编写的)。

In [66]: x=np.arange(12)

In [67]: np.reshape(x,(3,4))
Out[67]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

字符串
该方法可以接受元组或数字:

In [68]: x.reshape((3,4))
Out[68]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [69]: x.reshape(3,4)
Out[69]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])


该函数试图将第三个参数解释为order

In [70]: np.reshape(x,3,4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:57, in _wrapfunc(obj, method, *args, **kwds)
     56 try:
---> 57     return bound(*args, **kwds)
     58 except TypeError:
     59     # A TypeError occurs if the object does have such a method in its
     60     # class, but its signature is not identical to that of NumPy's. This
   (...)
     64     # Call _wrapit from within the except clause to ensure a potential
     65     # exception has a traceback chain.

TypeError: order must be str, not int

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
Cell In[70], line 1
----> 1 np.reshape(x,3,4)

File <__array_function__ internals>:200, in reshape(*args, **kwargs)

File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:298, in reshape(a, newshape, order)
    198 @array_function_dispatch(_reshape_dispatcher)
    199 def reshape(a, newshape, order='C'):
    200     """
    201     Gives a new shape to an array without changing its data.
    202 
   (...)
    296            [5, 6]])
    297     """
--> 298     return _wrapfunc(a, 'reshape', newshape, order=order)

File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:66, in _wrapfunc(obj, method, *args, **kwds)
     57     return bound(*args, **kwds)
     58 except TypeError:
     59     # A TypeError occurs if the object does have such a method in its
     60     # class, but its signature is not identical to that of NumPy's. This
   (...)
     64     # Call _wrapit from within the except clause to ensure a potential
     65     # exception has a traceback chain.
---> 66     return _wrapit(obj, method, *args, **kwds)

File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:43, in _wrapit(obj, method, *args, **kwds)
     41 except AttributeError:
     42     wrap = None
---> 43 result = getattr(asarray(obj), method)(*args, **kwds)
     44 if wrap:
     45     if not isinstance(result, mu.ndarray):

TypeError: order must be str, not int

In [71]: np.reshape(x,(3,4),'F')
Out[71]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])


该方法要求订单是一个关键字:

In [72]: x.reshape(3,4,'F')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[72], line 1
----> 1 x.reshape(3,4,'F')

TypeError: 'str' object cannot be interpreted as an integer

In [73]: x.reshape(3,4,order='F')
Out[73]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])
    
In [75]: x.reshape((3,4),'F')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[75], line 1
----> 1 x.reshape((3,4),'F')

TypeError: 'tuple' object cannot be interpreted as an integer

In [76]: x.reshape((3,4),order='F')
Out[76]: 
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])


将这些错误与newshape错误时的错误进行比较。相同的错误,但函数具有额外的wrapit分层。

In [77]: x.reshape((3,5))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[77], line 1
----> 1 x.reshape((3,5))

ValueError: cannot reshape array of size 12 into shape (3,5)

In [78]: np.reshape(x,(3,5))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[78], line 1
----> 1 np.reshape(x,(3,5))

File <__array_function__ internals>:200, in reshape(*args, **kwargs)

File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:298, in reshape(a, newshape, order)
    198 @array_function_dispatch(_reshape_dispatcher)
    199 def reshape(a, newshape, order='C'):
    200     """
    201     Gives a new shape to an array without changing its data.
    202 
   (...)
    296            [5, 6]])
    297     """
--> 298     return _wrapfunc(a, 'reshape', newshape, order=order)

File ~\miniconda3\lib\site-packages\numpy\core\fromnumeric.py:57, in _wrapfunc(obj, method, *args, **kwds)
     54     return _wrapit(obj, method, *args, **kwds)
     56 try:
---> 57     return bound(*args, **kwds)
     58 except TypeError:
     59     # A TypeError occurs if the object does have such a method in its
     60     # class, but its signature is not identical to that of NumPy's. This
   (...)
     64     # Call _wrapit from within the except clause to ensure a potential
     65     # exception has a traceback chain.
     66     return _wrapit(obj, method, *args, **kwds)

ValueError: cannot reshape array of size 12 into shape (3,5)


(这些错误追溯很长,因为ipython%xmode被设置为verbose

编辑

np.random.rand有这样的注解:

rand(d0, d1, ..., dn)

Random values in a given shape.

.. note::
    This is a convenience function for users porting code from Matlab,
    and wraps `random_sample`. That function takes a
    tuple to specify the size of the output, which is consistent with
    other NumPy functions like `numpy.zeros` and `numpy.ones`.


虽然numpy始终将形状显示为元组(即使是0 d和1d的情况),但也有函数/方法将其接受为单独的数字。本说明表明这是numpy的早期功能,从MATLAB仍然投射长阴影的日子起。
当然,在Python中,1,2,3(1,2,3)一样是一个元组。在像索引这样的上下文中,()是可选的,例如x[1,2,3]x[(1,2,3)]是一样的。两者都被解释为x.__getitem__((1,2,3))

相关问题