0으로 나누고 0을 반환하는 방법
파이썬에서 요소 현명한 나누기를 수행하려고하지만 0이 발생하면 몫이 0이되어야합니다.
예를 들면 :
array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])
array1 / array2 # should be np.array([0, 1, 2])
나는 항상 내 데이터를 통해 for 루프를 사용할 수 있지만 실제로 numpy의 최적화를 활용하려면 오류를 무시하는 대신 0으로 나누면 오류가 0을 반환하는 나누기 함수가 필요합니다.
내가 뭔가를 놓치고 있지 않는 한 numpy.seterr () 이 오류에 대해 값을 반환 할 수있는 것 같지 않습니다 . 누구든지 0으로 나누기 오류 처리를 설정하는 동안 numpy에서 최선을 다할 수있는 방법에 대한 다른 제안이 있습니까?
numpy v1.7 이상에서는 ufuncs 에 대한 "where"옵션을 활용할 수 있습니다. 한 줄로 작업을 수행 할 수 있으며 errstate 컨텍스트 관리자를 다룰 필요가 없습니다.
>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0. 0. 0. 1. 1.5]
이 경우 b가 0이 아닌 곳에서 나누기 계산을 수행합니다. b가 0과 같으면 원래 'out'인수에서 제공 한 값에서 변경되지 않습니다.
@Franck Dernoncourt의 답변을 바탕으로 -1/0 수정 :
def div0( a, b ):
""" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide( a, b )
c[ ~ np.isfinite( c )] = 0 # -inf inf NaN
return c
div0( [-1, 0, 1], 0 )
array([0, 0, 0])
다른 답변을 바탕으로 다음을 개선합니다.
0/0
추가invalid='ignore'
하여 처리numpy.errstate()
- 도입
numpy.nan_to_num()
변환np.nan
에0
.
암호:
import numpy as np
a = np.array([0,0,1,1,2], dtype='float')
b = np.array([0,1,0,1,3], dtype='float')
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a,b)
c[c == np.inf] = 0
c = np.nan_to_num(c)
print('c: {0}'.format(c))
산출:
c: [ 0. 0. 0. 1. 0.66666667]
한 줄짜리 (경고 발생)
np.nan_to_num(array1 / array2)
두 단계로 시도하십시오. 먼저 분할 한 다음 교체하십시오.
with numpy.errstate(divide='ignore'):
result = numerator / denominator
result[denominator == 0] = 0
이 numpy.errstate
줄은 선택 사항이며 numpy가 0으로 나누는 "오류"에 대해 알려주지 못하도록 막습니다. 이미 그렇게하려고했기 때문에이 경우를 처리합니다.
You can also replace based on inf
, only if the array dtypes are floats, as per this answer:
>>> a = np.array([1,2,3], dtype='float')
>>> b = np.array([0,1,3], dtype='float')
>>> c = a / b
>>> c
array([ inf, 2., 1.])
>>> c[c == np.inf] = 0
>>> c
array([ 0., 2., 1.])
One answer I found searching a related question was to manipulate the output based upon whether the denominator was zero or not.
Suppose arrayA
and arrayB
have been initialized, but arrayB
has some zeros. We could do the following if we want to compute arrayC = arrayA / arrayB
safely.
In this case, whenever I have a divide by zero in one of the cells, I set the cell to be equal to myOwnValue
, which in this case would be zero
myOwnValue = 0
arrayC = np.zeros(arrayA.shape())
indNonZeros = np.where(arrayB != 0)
indZeros = np.where(arrayB = 0)
# division in two steps: first with nonzero cells, and then zero cells
arrayC[indNonZeros] = arrayA[indNonZeros] / arrayB[indNonZeros]
arrayC[indZeros] = myOwnValue # Look at footnote
Footnote: In retrospect, this line is unnecessary anyways, since arrayC[i]
is instantiated to zero. But if were the case that myOwnValue != 0
, this operation would do something.
An other solution worth mentioning :
>>> a = np.array([1,2,3], dtype='float')
>>> b = np.array([0,1,3], dtype='float')
>>> b_inv = np.array([1/i if i!=0 else 0 for i in b])
>>> a*b_inv
array([0., 2., 1.])
참고URL : https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero
'Development Tip' 카테고리의 다른 글
내용과 동일한 너비 (0) | 2020.10.08 |
---|---|
Sequelize.js 쿼리를 삭제 하시겠습니까? (0) | 2020.10.08 |
DDoS 보호를 활성화하는 방법은 무엇입니까? (0) | 2020.10.08 |
레이아웃 내부에 레이아웃을 포함하는 방법은 무엇입니까? (0) | 2020.10.08 |
원격 서버에서 Tensorboard를 어떻게 실행할 수 있습니까? (0) | 2020.10.08 |