首页 文章

Numpy - AttributeError:'Zero' object没有属性'exp'

提问于
浏览
0

我在解决运行时断开的东西之间的差异时遇到了麻烦,但在python控制台中使用完全相同的数据和操作,让它工作正常 .

# f_err - currently has value 1.11819388872025
# l_scales - currently a numpy array [1.17840183376334 1.13456764589809]
sq_euc_dists = self.se_term(x1, x2, l_scales) # this is fine. It calls cdists on x1/l_scales, x2/l_scales vectors
return (f_err**2) * np.exp(-0.5 * sq_euc_dists) # <-- errors on this line

我得到的错误是

AttributeError: 'Zero' object has no attribute 'exp'

但是,在错误输出之后,在控制台中调用那些完全相同的行,使用相同的f_err,l_scales和x1,x2,不知何故不会产生错误 .

我没有找到专门提到'零'对象错误的帖子,而我发现的非'零'对象似乎并不适用于我的情况 .

编辑:它有点缺乏信息,所以这是一个实际的(提取的)可运行的示例,带有样本数据,我直接从失败的运行中获取,当在隔离运行时工作正常/我无法重现错误,除了在运行时 .

请注意,下面的sqeucld_dist函数非常糟糕,我应该使用scipy的cdist . 但是,因为我在实际数据中使用了带有超过15个偏导数的矩阵元素渐变的sympy符号,所以cdist不是一个选项,因为它不处理任意对象 .

import numpy as np

def se_term(x1, x2, l):
    return sqeucl_dist(x1/l, x2/l)

def sqeucl_dist(x, xs):
    return np.sum([(i-j)**2 for i in x for j in xs], axis=1).reshape(x.shape[0], xs.shape[0])


x = np.array([[-0.29932052, 0.40997373], [0.40203481, 2.19895326], [-0.37679417, -1.11028267], [-2.53012051, 1.09819485], [0.59390005, 0.9735], [0.78276777, -1.18787904], [-0.9300892, 1.18802775], [0.44852545, -1.57954101], [1.33285028, -0.58594779], [0.7401607, 2.69842268], [-2.04258086, 0.43581565], [0.17353396, -1.34430191], [0.97214259, -1.29342284], [-0.11103534, -0.15112815], [0.41541759, -1.51803154], [-0.59852383, 0.78442389], [2.01323359, -0.85283772], [-0.14074266, -0.63457529], [-0.49504797, -1.06690869], [-0.18028754, -0.70835799], [-1.3794126, 0.20592016], [-0.49685373, -1.46109525], [-1.41276934, -0.66472598], [-1.44173868, 0.42678815], [0.64623684, 1.19927771], [-0.5945761, -0.10417961]])
f_err = 1.11466725760716
l = [1.18388412685279, 1.02290811104357]
result = (f_err**2) * np.exp(-0.5 * se_term(x, x, l)) # This runs fine, but fails with the exact same calls and data during runtime

任何帮助非常感谢!

1 回答

  • 1

    以下是重现您所看到的错误的方法:

    import sympy
    import numpy
    
    zero = sympy.sympify('0')
    
    numpy.exp(zero)
    

    您将看到您所看到的相同异常 .

    您可以通过将代码更改为以下内容(低效率)来解决此问题 .

    def sqeucl_dist(x, xs):
        return np.sum([np.vectorize(float)(i-j)**2 for i in x for j in xs], 
                      axis=1).reshape(x.shape[0], xs.shape[0])
    

    最好使用lambdify修复渐变函数 .

    这是lambdify如何在部分d上使用的示例

    from sympy.abc import x, y, z
    expression = x**2 + sympy.sin(y) + z
    derivatives = [expression.diff(var, 1) for var in [x, y, z]]
    

    derivatives 现在是 [2*x, cos(y), 1] ,一个Sympy表达式列表 . 要创建一个将在一组特定值上以数字方式对其进行求值的函数,我们使用 lambdify 如下(将 'numpy' 作为参数传递,就像使用 numpy.cos 而不是 sympy.cos ):

    derivative_calc = sympy.lambdify((x, y, z), derivatives, 'numpy')
    

    现在 derivative_calc(1, 2, 3) 将返回 [2, -0.41614683654714241, 1] . 这些是 intnumpy.float64 .

    旁注: np.exp(M) 将计算 M 的每个元素的元素指数 . 如果您尝试使用矩阵指数,则需要np.linalg.exmp .

相关问题