Autograd typeerror при нахождении градиента scipy.stat.norm.pdf (x) - PullRequest
0 голосов
/ 16 сентября 2018

Я хочу найти простой градиент нормального распределения pdf с scipy.stats.norm, используя autograd в Python.

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

1 Ответ

0 голосов
/ 06 февраля 2019

Вам нужно импортировать scipy из autograd, так как он соответствующим образом обернет функции 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))
...