- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在numpy.reshape
的文档中,它说:
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
我的问题是,numpy什么时候会选择返回一个新 View ,什么时候复制整个数组?关于 reshape
的行为,是否有任何一般原则告诉人们,或者它只是不可预测的?谢谢。
最佳答案
@mgillson 找到的链接似乎解决了“我如何判断它是否制作了副本”的问题,而不是“我如何预测它”或理解它制作副本的原因。至于测试,我喜欢用A.__array_interfrace__
.
如果您尝试将值分配给 reshape 后的数组,并希望同时更改原始数组,这很可能会成为一个问题。而且我很难找到问题所在的 SO 案例。
复制 reshape 会比非复制 reshape 慢一点,但我还是想不出会导致整个代码变慢的情况。如果您使用的数组太大以至于最简单的操作会产生内存错误,那么副本也可能是个问题。
reshape 数据缓冲区中的值后,需要按连续顺序排列,即“C”或“F”。例如:
In [403]: np.arange(12).reshape(3,4,order='C')
Out[403]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [404]: np.arange(12).reshape(3,4,order='F')
Out[404]:
array([[ 0, 3, 6, 9],
[ 1, 4, 7, 10],
[ 2, 5, 8, 11]])
如果初始顺序如此“困惑”以至于无法返回这样的值,它将进行复制。 Reshape after transpose 可能会这样做(请参阅下面的示例)。使用 stride_tricks.as_strided
的游戏也可能如此.这些是我能想到的唯一情况。
In [405]: x=np.arange(12).reshape(3,4,order='C')
In [406]: y=x.T
In [407]: x.__array_interface__
Out[407]:
{'version': 3,
'descr': [('', '<i4')],
'strides': None,
'typestr': '<i4',
'shape': (3, 4),
'data': (175066576, False)}
In [408]: y.__array_interface__
Out[408]:
{'version': 3,
'descr': [('', '<i4')],
'strides': (4, 16),
'typestr': '<i4',
'shape': (4, 3),
'data': (175066576, False)}
y
,转置,具有相同的“数据”指针。转置是在不更改或复制数据的情况下执行的,它只是用新的 shape
创建了一个新对象。 , strides
, 和 flags
.
In [409]: y.flags
Out[409]:
C_CONTIGUOUS : False
F_CONTIGUOUS : True
...
In [410]: x.flags
Out[410]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
...
y
是订单'F'。现在尝试 reshape 它
In [411]: y.shape
Out[411]: (4, 3)
In [412]: z=y.reshape(3,4)
In [413]: z.__array_interface__
Out[413]:
{...
'shape': (3, 4),
'data': (176079064, False)}
In [414]: z
Out[414]:
array([[ 0, 4, 8, 1],
[ 5, 9, 2, 6],
[10, 3, 7, 11]])
z
是副本,其data
缓冲区指针不同。它的值没有以任何类似于 x
的方式排列。或 y
, 没有 0,1,2,...
.
但只是 reshape x
不产生副本:
In [416]: w=x.reshape(4,3)
In [417]: w
Out[417]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [418]: w.__array_interface__
Out[418]:
{...
'shape': (4, 3),
'data': (175066576, False)}
整理 y
与y.reshape(-1)
相同;它作为副本生成:
In [425]: y.reshape(-1)
Out[425]: array([ 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11])
In [426]: y.ravel().__array_interface__['data']
Out[426]: (175352024, False)
像这样将值赋给一个拼凑的数组可能是最有可能在复制时产生错误的情况。例如,x.ravel()[::2]=99
更改 x
的所有其他值和 y
(分别为列和行)。但是y.ravel()[::2]=0
由于此复制,什么都不做。
因此转置后 reshape 是最有可能的复制场景。我很乐意探索其他可能性。
编辑: y.reshape(-1,order='F')[::2]=0
确实改变了 y
的值.对于兼容的顺序, reshape 不会生成副本。
@mgillson 链接中的一个答案,https://stackoverflow.com/a/14271298/901925 , 指出 A.shape=...
语法防止复制。如果不复制就无法更改形状,则会引发错误:
In [441]: y.shape=(3,4)
...
AttributeError: incompatible shape for a non-contiguous array
reshape
中也提到了这一点文档
If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array::
SO 关于 reshape 以下 as_strided
的问题:
reshaping a view of a n-dimensional array without using reshape
和
Numpy View Reshape Without Copy (2d Moving/Sliding Window, Strides, Masked Memory Structures)
==========================
这是我翻译的第一个剪辑 shape.c/_attempt_nocopy_reshape
进入 Python。它可以像这样运行:
newstrides = attempt_reshape(numpy.zeros((3,4)), (4,3), False)
import numpy # there's an np variable in the code
def attempt_reshape(self, newdims, is_f_order):
newnd = len(newdims)
newstrides = numpy.zeros(newnd+1).tolist() # +1 is a fudge
self = numpy.squeeze(self)
olddims = self.shape
oldnd = self.ndim
oldstrides = self.strides
#/* oi to oj and ni to nj give the axis ranges currently worked with */
oi,oj = 0,1
ni,nj = 0,1
while (ni < newnd) and (oi < oldnd):
print(oi, ni)
np = newdims[ni];
op = olddims[oi];
while (np != op):
if (np < op):
# /* Misses trailing 1s, these are handled later */
np *= newdims[nj];
nj += 1
else:
op *= olddims[oj];
oj += 1
print(ni,oi,np,op,nj,oj)
#/* Check whether the original axes can be combined */
for ok in range(oi, oj-1):
if (is_f_order) :
if (oldstrides[ok+1] != olddims[ok]*oldstrides[ok]):
# /* not contiguous enough */
return 0;
else:
#/* C order */
if (oldstrides[ok] != olddims[ok+1]*oldstrides[ok+1]) :
#/* not contiguous enough */
return 0;
# /* Calculate new strides for all axes currently worked with */
if (is_f_order) :
newstrides[ni] = oldstrides[oi];
for nk in range(ni+1,nj):
newstrides[nk] = newstrides[nk - 1]*newdims[nk - 1];
else:
#/* C order */
newstrides[nj - 1] = oldstrides[oj - 1];
#for (nk = nj - 1; nk > ni; nk--) {
for nk in range(nj-1, ni, -1):
newstrides[nk - 1] = newstrides[nk]*newdims[nk];
nj += 1; ni = nj
oj += 1; oi = oj
print(olddims, newdims)
print(oldstrides, newstrides)
# * Set strides corresponding to trailing 1s of the new shape.
if (ni >= 1) :
print(newstrides, ni)
last_stride = newstrides[ni - 1];
else :
last_stride = self.itemsize # PyArray_ITEMSIZE(self);
if (is_f_order) :
last_stride *= newdims[ni - 1];
for nk in range(ni, newnd):
newstrides[nk] = last_stride;
return newstrides
关于python - 使用 reshape() 时 numpy 何时复制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995289/
我在网上搜索但没有找到任何合适的文章解释如何使用 javascript 使用 WCF 服务,尤其是 WebScriptEndpoint。 任何人都可以对此给出任何指导吗? 谢谢 最佳答案 这是一篇关于
我正在编写一个将运行 Linux 命令的 C 程序,例如: cat/etc/passwd | grep 列表 |剪切-c 1-5 我没有任何结果 *这里 parent 等待第一个 child (chi
所以我正在尝试处理文件上传,然后将该文件作为二进制文件存储到数据库中。在我存储它之后,我尝试在给定的 URL 上提供文件。我似乎找不到适合这里的方法。我需要使用数据库,因为我使用 Google 应用引
我正在尝试制作一个宏,将下面的公式添加到单元格中,然后将其拖到整个列中并在 H 列中复制相同的公式 我想在 F 和 H 列中输入公式的数据 Range("F1").formula = "=IF(ISE
问题类似于this one ,但我想使用 OperatorPrecedenceParser 解析带有函数应用程序的表达式在 FParsec . 这是我的 AST: type Expression =
我想通过使用 sequelize 和 node.js 将这个查询更改为代码取决于在哪里 select COUNT(gender) as genderCount from customers where
我正在使用GNU bash,版本5.0.3(1)-发行版(x86_64-pc-linux-gnu),我想知道为什么简单的赋值语句会出现语法错误: #/bin/bash var1=/tmp
这里,为什么我的代码在 IE 中不起作用。我的代码适用于所有浏览器。没有问题。但是当我在 IE 上运行我的项目时,它发现错误。 而且我的 jquery 类和 insertadjacentHTMl 也不
我正在尝试更改标签的innerHTML。我无权访问该表单,因此无法编辑 HTML。标签具有的唯一标识符是“for”属性。 这是输入和标签的结构:
我有一个页面,我可以在其中返回用户帖子,可以使用一些 jquery 代码对这些帖子进行即时评论,在发布新评论后,我在帖子下插入新评论以及删除 按钮。问题是 Delete 按钮在新插入的元素上不起作用,
我有一个大约有 20 列的“管道分隔”文件。我只想使用 sha1sum 散列第一列,它是一个数字,如帐号,并按原样返回其余列。 使用 awk 或 sed 执行此操作的最佳方法是什么? Accounti
我需要将以下内容插入到我的表中...我的用户表有五列 id、用户名、密码、名称、条目。 (我还没有提交任何东西到条目中,我稍后会使用 php 来做)但由于某种原因我不断收到这个错误:#1054 - U
所以我试图有一个输入字段,我可以在其中输入任何字符,但然后将输入的值小写,删除任何非字母数字字符,留下“。”而不是空格。 例如,如果我输入: 地球的 70% 是水,-!*#$^^ & 30% 土地 输
我正在尝试做一些我认为非常简单的事情,但出于某种原因我没有得到想要的结果?我是 javascript 的新手,但对 java 有经验,所以我相信我没有使用某种正确的规则。 这是一个获取输入值、检查选择
我想使用 angularjs 从 mysql 数据库加载数据。 这就是应用程序的工作原理;用户登录,他们的用户名存储在 cookie 中。该用户名显示在主页上 我想获取这个值并通过 angularjs
我正在使用 autoLayout,我想在 UITableViewCell 上放置一个 UIlabel,它应该始终位于单元格的右侧和右侧的中心。 这就是我想要实现的目标 所以在这里你可以看到我正在谈论的
我需要与 MySql 等效的 elasticsearch 查询。我的 sql 查询: SELECT DISTINCT t.product_id AS id FROM tbl_sup_price t
我正在实现代码以使用 JSON。 func setup() { if let flickrURL = NSURL(string: "https://api.flickr.com/
我尝试使用for循环声明变量,然后测试cols和rols是否相同。如果是,它将运行递归函数。但是,我在 javascript 中执行 do 时遇到问题。有人可以帮忙吗? 现在,在比较 col.1 和
我举了一个我正在处理的问题的简短示例。 HTML代码: 1 2 3 CSS 代码: .BB a:hover{ color: #000; } .BB > li:after {
我是一名优秀的程序员,十分优秀!