numpy:FutureWarning:未来的版本将不会从broadcast_array创建可写数组,显式设置可写标志以避免此警告

ttisahbt  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(135)

以下代码片段在numpy v1.24中引发警告:

import numpy as np
x = np.array(0)
y = np.array([1, 2, 3])
x_, y_ = np.broadcast_arrays(x, y)

x_.flags.writeable
# FutureWarning: future versions will not create a writeable array from broadcast_array. Set the writable flag explicitly to avoid this warning.

如何缓解?

e3bfsja2

e3bfsja21#

考虑到numpy.broadcast_arrays的结果在未来版本的numpy中是不可写的,最好预测到变化并显式地将数组设置为只读:

x_.flags.writeable = False

一旦完成,访问x_.flags.writeable将不会创建警告。
此外,将广播数组x_设置为只读对基本数组x没有任何变化:

x_.flags.writeable
# False

x.flags.writeable
# True
yk9xbfzb

yk9xbfzb2#

使用您的代码(在numpy 1.24中)

In [340]: x_
Out[340]: array([0, 0, 0])

In [341]: x_.strides
Out[341]: (0,)

跨距意味着x_的所有元素都是相同的,x的一个元素的view

In [342]: x_[0]
Out[342]: 0

设置元素可以工作,但也会引发警告:

In [343]: x_[0]=1
C:\Users\14256\AppData\Local\Temp\ipykernel_12988\3649538002.py:1: DeprecationWarning: Numpy has detected that you (may be) writing to an array with
overlapping memory from np.broadcast_arrays. If this is intentional
set the WRITEABLE flag True or make a copy immediately before writing.
  x_[0]=1

在这个版本中,可写标志仍然是True:

In [346]: x_.flags
Out[346]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False

In [347]: x_
Out[347]: array([1, 1, 1])
In [349]: x
Out[349]: array(1)

尝试设置x_的3个元素,结果只有最后一个有效:

In [350]: x_[:]=[1,2,3]

In [351]: x
Out[351]: array(3)

In [352]: x_
Out[352]: array([3, 3, 3])

相关问题