0

我想在 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))

但是,我得到了这个打字错误:

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

4

1 回答 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))
于 2019-02-06T00:26:12.507 回答