Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Allow custom bandwidth functions in KDEUnivariate fit #6997

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions statsmodels/nonparametric/kde.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,10 @@ def kdensity(X, kernel="gau", bw="normal_reference", weights=None, gridsize=None

# if bw is None, select optimal bandwidth for kernel
try:
bw = float(bw)
if callable(bw):
dbivolaru marked this conversation as resolved.
Show resolved Hide resolved
bw = float(bw(X, kern))
else:
bw = float(bw)
except:
bw = bandwidths.select_bandwidth(X, bw, kern)
bw *= adjust
Expand Down Expand Up @@ -454,7 +457,10 @@ def kdensityfft(X, kernel="gau", bw="normal_reference", weights=None, gridsize=N
kern = kernel_switch[kernel]()

try:
bw = float(bw)
if callable(bw):
dbivolaru marked this conversation as resolved.
Show resolved Hide resolved
bw = bw(X, kern) # user passed a callable custom bandwidth function
else:
bw = float(bw)
except:
bw = bandwidths.select_bandwidth(X, bw, kern) # will cross-val fit this pattern?
bw *= adjust
Expand Down
16 changes: 16 additions & 0 deletions statsmodels/nonparametric/tests/test_kde.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,19 @@ def test_fit_self(reset_randomstate):
kde = KDE(x)
assert isinstance(kde, KDE)
assert isinstance(kde.fit(), KDE)


class TestKDECustomBandwidth(object):

@classmethod
def setup_class(cls):
cls.kde = KDE(Xi)
cls.weights_200 = np.linspace(1, 100, 200)
cls.weights_100 = np.linspace(1, 100, 100)

def test_check_is_fit_ok_with_custom_bandwidth(self):
dbivolaru marked this conversation as resolved.
Show resolved Hide resolved
def custom_bw(X, kern):
return np.std(X) * len(X)
kde = self.kde.fit(bw=custom_bw)
assert isinstance(kde, KDE)