尝试/除非捕获错误

时间:2018-02-25 14:41:32

标签: python numpy error-handling try-catch

我试图使用try / except来处理除零错误,但是除了似乎没有抓住错误,我无法弄清楚原因。< / p>

import numpy as np

A = np.array([[0.5,0,0.25,0.125,0.05],[0.5,0.5,0.5,0.5,0.5]])
Y = np.array([[0,1,0,1,1],[0,0,0,0,1]])
p = np.shape(A)[0]
q = np.shape(A)[1]
m = 2
try:
    dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) 
except Exception:
    dA = np.zeros((p,q))

它返回除零误差和乘法中遇到的无效值(因为除以零错误),但它会杀死程序而不是做除了之外的事情。

RuntimeWarning: divide by zero encountered in true_divide
  dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A))
RuntimeWarning: invalid value encountered in multiply
  dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A))

我尝试指定错误而不仅仅是Exception,但这也不起作用。还有什么可能是问题?

1 个答案:

答案 0 :(得分:3)

如果它是numpy数组则除零,不会抛出异常,但只给出警告并给出inf值。

您可以使用numpy.isfinite检查数组中的值是否有限(而不是nan或inf)。

A = np.array([[0.5,0,0.25,0.125,0.05],[0.5,0.5,0.5,0.5,0.5]])
Y = np.array([[0,1,0,1,1],[0,0,0,0,1]])
p = np.shape(A)[0]
q = np.shape(A)[1]
m = 2
try:
    dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) 
except Exception:
    dA = np.zeros((p,q))

if not np.isfinite(dA).all():
    dA = np.zeros((p,q))

如果您确定您的元素是numpy数组,则不需要例外:

dA = (-1 / m) * ((Y - A) / (A - np.square(A))) * (A * (1 - A)) 
if not np.isfinite(dA).all():
    dA = np.zeros((p,q))