kef*_*ich 2 python arrays numpy multidimensional-array
测试数组是否可以广播到给定形状的最佳方法是什么?
trying的“pythonic”方法不适用于我的情况,因为目的是对操作进行惰性评估。
我在问如何在is_broadcastable下面实施:
>>> x = np.ones([2,2,2])
>>> y = np.ones([2,2])
>>> is_broadcastable(x,y)
True
>>> y = np.ones([2,3])
>>> is_broadcastable(x,y)
False
Run Code Online (Sandbox Code Playgroud)
或者更好:
>>> is_broadcastable(x.shape, y.shape)
Run Code Online (Sandbox Code Playgroud)
我真的认为你们想多了,为什么不简单点呢?
def is_broadcastable(shp1, shp2):
for a, b in zip(shp1[::-1], shp2[::-1]):
if a == 1 or b == 1 or a == b:
pass
else:
return False
return True
Run Code Online (Sandbox Code Playgroud)
如果您只想避免实现具有给定形状的数组,可以使用 as_strided:
import numpy as np
from numpy.lib.stride_tricks import as_strided
def is_broadcastable(shp1, shp2):
x = np.array([1])
a = as_strided(x, shape=shp1, strides=[0] * len(shp1))
b = as_strided(x, shape=shp2, strides=[0] * len(shp2))
try:
c = np.broadcast_arrays(a, b)
return True
except ValueError:
return False
is_broadcastable((1000, 1000, 1000), (1000, 1, 1000)) # True
is_broadcastable((1000, 1000, 1000), (3,)) # False
Run Code Online (Sandbox Code Playgroud)
这是内存高效的,因为 a 和 b 都由单个记录支持
| 归档时间: |
|
| 查看次数: |
1949 次 |
| 最近记录: |