gpt4 book ai didi

python - 这是创建 numpy 数组的只读 View 的正确方法吗?

转载 作者:行者123 更新时间:2023-12-04 14:15:19 24 4
gpt4 key购买 nike

我想创建一个对 NumPy 数组的只读引用。这是制作 b 的正确方法吗?对 a 的只读引用( a 是任何 NumPy 数组)?

def get_readonly_view(a):
b = a.view()
b.flags.writeable = False
return b

具体来说,我想确保上述内容不会“复制” a 的内容。 ? (我尝试用 np.shares_memory 测试它并返回 True 。但我不确定这是否是正确的测试。)

另外我想知道是否 get_readonly_view已经在 NumPy 中实现了吗?

更新。 建议将数组转换为类属性以使其只读。我认为这不起作用:
import numpy as np

class Foo:

def __init__(self):
self._a = np.arange(15).reshape((3, 5))


@property
def a(self):
return self._a


def bar(self):
print(self._a)

但是客户端可以更改 _a的内容:
>> baz = Foo()
>> baz.bar()
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
>> baz.a[1, 2] = 10
>> baz.bar()
[[ 0 1 2 3 4]
[ 5 6 10 8 9]
[10 11 12 13 14]]

而我想要 baz.a[1, 2] = 10引发异常。

最佳答案

您的方法似乎是创建 read-only 的建议方法。 view .

特别是arr.view() (也可以写成切片 arr[:] )将创建对 arr 的引用, 同时修改 writeable flag 是使 NumPy 数组只读的建议方法。

该文档还提供了一些关于 writeable 继承的附加信息。属性(property):

The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.



只是重申并检查正在发生的事情:
import numpy as np


def get_readonly_view(arr):
result = arr.view()
result.flags.writeable = False
return result


a = np.zeros((2, 2))
b = get_readonly_view(a)

print(a.flags)
# C_CONTIGUOUS : True
# F_CONTIGUOUS : False
# OWNDATA : True
# WRITEABLE : True
# ALIGNED : True
# WRITEBACKIFCOPY : False
# UPDATEIFCOPY : False
print(b.flags)
# C_CONTIGUOUS : True
# F_CONTIGUOUS : False
# OWNDATA : False
# WRITEABLE : False
# ALIGNED : True
# WRITEBACKIFCOPY : False
# UPDATEIFCOPY : False

print(a.base)
# None
print(b.base)
# [[0. 0.]
# [0. 0.]]

a[1, 1] = 1.0
# ...works
b[0, 0] = 1.0
# raises ValueError: assignment destination is read-only

关于python - 这是创建 numpy 数组的只读 View 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com