[英]Why is numpy.ravel() required in this code that produces small multiples?
[英]Why is numpy.ravel returning a copy?
在以下示例中:
>>> import numpy as np
>>> a = np.arange(10)
>>> b = a[:,np.newaxis]
>>> c = b.ravel()
>>> np.may_share_memory(a,c)
False
為什么numpy.ravel
返回我的數組的副本? 它不應該只是返回a
?
編輯:
我剛剛發現np.squeeze
沒有返回副本。
>>> b = a[:,np.newaxis]
>>> c = b.squeeze()
>>> np.may_share_memory(a,c)
True
在這種情況下,為什么squeeze
和ravel
之間存在差異?
編輯:
正如mgilson指出, newaxis
標記數組作為不連續的,這就是為什么ravel
返回一個副本。
所以,新問題是為什么newaxis
將數組標記為不連續。
盡管如此,這個故事更加怪異:
>>> a = np.arange(10)
>>> b = np.expand_dims(a,axis=1)
>>> b.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> c = b.ravel()
>>> np.may_share_memory(a,c)
True
根據expand_dims
的文檔,它應該等同於newaxis
。
這可能不是您問題的最佳答案,但看起來插入newaxis會導致numpy將陣列視為非連續的 - 可能用於廣播目的:
>>> a=np.arange(10)
>>> b=a[:,None]
>>> a.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> b.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
但是,重塑不會導致:
>>> c=a.reshape(10,1)
>>> c.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
那些數組確實共享相同的內存:
>>> np.may_share_memory(c.ravel(),a)
True
編輯
np.expand_dims
實際上是使用reshape
實現的,這就是它工作的原因(這是我假設的文檔中的一個小錯誤)。 這是源代碼(沒有docstring):
def expand_dims(a,axis):
a = asarray(a)
shape = a.shape
if axis < 0:
axis = axis + len(shape) + 1
return a.reshape(shape[:axis] + (1,) + shape[axis:])
看起來它可能與步幅有關:
>>> c = np.expand_dims(a, axis=1)
>>> c.strides
(8, 8)
>>> b = a[:, None]
>>> b.strides
(8, 0)
>>> b.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> b.strides = (8, 8)
>>> b.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
我不確定維度1在這里可以產生什么不同,但看起來這就是讓numpy將陣列視為不連續的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.