2014-07-14 2 views
1

어레이를 주어진 모양으로 브로드 캐스트 할 수 있는지 테스트하는 가장 좋은 방법은 무엇입니까?배열을 도형에 브로드 캐스팅 할 수 있는지 테스트하십시오.

"pythonic"접근 방식은 나의 경우에는 효과가 없습니다. 왜냐하면 의도적으로 작업을 게을러 르게 평가하기 때문입니다. 더 나은 아직

>>> 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 

또는 :

나는 is_broadcastable 아래 구현하는 방법을 부탁 해요 당신은 np.broadcast을 사용할 수

>>> is_broadcastable(x.shape, y.shape) 
+0

참조 : http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html –

답변

3

나는 정말로 너희들이 이것을 생각하고 있다고 생각한다. 왜 단순하게 유지하지 않는가?

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 
+0

나는 이것에 문제가 있다고 생각하지 않는다. 내가 놓칠지도 모르는 미묘한 추가 규칙이 없다, 거기 있니? – keflavich

3

. 예 :

In [47]: x = np.ones([2,2,2]) 

In [48]: y = np.ones([2,3]) 

In [49]: try: 
    ....:  b = np.broadcast(x, y) 
    ....:  print "Result has shape", b.shape 
    ....: except ValueError: 
    ....:  print "Not compatible for broadcasting" 
    ....:  
Not compatible for broadcasting 

In [50]: y = np.ones([2,2]) 

In [51]: try: 
    ....:  b = np.broadcast(x, y) 
    ....:  print "Result has shape", b.shape 
    ....: except ValueError: 
    ....:  print "Not compatible for broadcasting" 
    ....: 
Result has shape (2, 2, 2) 

지연 평가를 구현하려면 np.broadcast_arrays이 유용 할 수 있습니다. 당신은 그냥 주어진 모양으로 배열을 구체화하지 않도록하려면

+1

'broadcast_arrays' 내가 게으름을 얻기 위하여 무엇을 찾고 있었다,하지만 난 여전히 필요 검증 단계 - 형태 B가 손에 배열되어 있지 않다는 가정하에 모양 A가 B 형태로 방송 될 수 있다면 어떻게 테스트 할 수 있습니까? – keflavich

4

, 당신은 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 

이것은 이후, 메모리 효율적이고 B가 모두 하나의 레코드에 의해 백업됩니다

관련 문제