0

I'm trying to integrate a two-dimension KDE function with SciPy following this answer, but I'm getting an error that I provide more arguments than are required.

from scipy import integrate
import numpy as np
import scipy.stats as sts

# data 
rvs = np.append(stats.norm.rvs(loc=0,scale=3,size=(2000,1)),
                stats.norm.rvs(loc=1,scale=2,size=(2000,1)),
                axis=1)

# fit kde
kde = stats.kde.gaussian_kde(rvs.T)

# failed attempts to calculate the integral:
print(integrate.nquad(kde, [[-1, 1],[-1, 1]])) # --> error: evaluate() takes 2 positional arguments but 3 were given
print(integrate.dblquad(kde, -1, 1, -1, 1)) # --> error: evaluate() takes 2 positional arguments but 3 were given

According to the documentation for Scipy.nquad, I must provide a func object as the first argument. Is the KDE missing a required type? Can I extract the function that works for integration from the KDE object?

Ailurophile
  • 2,552
  • 7
  • 21
  • 46
Yanirmr
  • 923
  • 8
  • 25

1 Answers1

1

Your issue is not with the integrate function, it is with how the kde function accepts arguments - it only takes one argument (and a class instance argument, which is why it says 2 arguments). So you need to pack your input arguments to kde in a list or a tuple.

To align with how the integrate function passes arguments, you could just make a lambda from kde and apply the integrate function on that, like so

kde2 = lambda a, b: kde([a,b])
print(integrate.nquad(kde2, [[-1, 1],[-1, 1]]))
print(integrate.dblquad(kde2, -1, 1, -1, 1))
oskros
  • 3,101
  • 2
  • 9
  • 28
  • This calculation returns 2-dim result ```(0.08394255210560318, 9.319495409343757e-16)```. Why? – Yanirmr May 04 '21 at 11:31
  • 1
    I believe the second result value is the error on the integration. in the documentation it states: `The maximum of the estimates of the absolute error in the various integration results.` – oskros May 04 '21 at 11:33