Autograd类型错误发现s cipy.stat.norm.pdf的梯度时(x)的

问题描述 投票:0回答:1

我想找到与使用Python autograd scipy.stats.norm正态分布PDF的一个简单的梯度。

import scipy.stats as stat
import autograd.numpy as np
from autograd import grad

def f(x):
    return stat.norm.pdf(x, 0.0, 1.0)

grad_f = grad(f)

print(grad_f(-1.0))

不过,我得到这个typerror:

Traceback (most recent call last):
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/autograd/core.py", line 62, in forward_pass
    try: end_node = fun(*args, **kwargs)
  File "error.py", line 7, in f
    return stat.norm.pdf(x, 0.0, 1.0)
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 1657, in pdf
    putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported typesaccording to the casting rule ''safe''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "error.py", line 11, in <module>
    print(grad_f(-1.0))
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/autograd/core.py", line 21, in gradfun
    return backward_pass(*forward_pass(fun,args,kwargs,argnum))
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/autograd/core.py", line 63, in forward_pass
    except Exception as e: add_extra_error_message(e)
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/autograd/core.py", line 392, in add_extra_error_message
    raise_(etype, value, traceback)
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/future/utils/__init__.py", line 413, in raise_
    raise exc.with_traceback(tb)
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/autograd/core.py", line 62, in forward_pass
    try: end_node = fun(*args, **kwargs)
  File "error.py", line 7, in f
    return stat.norm.pdf(x, 0.0, 1.0)
  File "/Users/Lars/anaconda3/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 1657, in pdf
    putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported typesaccording to the casting rule ''safe''

对不起,我的代码过载。我不知道什么可能错。据我所知,autograd支持)scipy.stats.norm.pdf的梯度(/ CDF()/ logpdf()/ logcdf(),由代码https://github.com/HIPS/autograd/blob/master/autograd/scipy/stats/norm.py所指示

python scipy typeerror normal-distribution autograd
1个回答
1
投票

你需要从autograd进口SciPy的,因为它会适当地包装SciPy的职能。以下工作:

import autograd.scipy.stats as stat     # note this import
import autograd.numpy as np
from autograd import grad

def f(x):
    return stat.norm.pdf(x, 0.0, 1.0)

grad_f = grad(f)

print(grad_f(-1.0))
© www.soinside.com 2019 - 2024. All rights reserved.