Created
November 12, 2019 12:14
-
-
Save LuxXx/dbff133b0c39dbcbfc20396217f75e50 to your computer and use it in GitHub Desktop.
Kernel Density Estimation Bandwith Slider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "cells": [ | |
| { | |
| "cell_type": "code", | |
| "execution_count": 1, | |
| "metadata": {}, | |
| "outputs": [], | |
| "source": [ | |
| "from ipywidgets import interact\n", | |
| "import numpy as np\n", | |
| "import matplotlib.pyplot as plt" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "execution_count": 2, | |
| "metadata": {}, | |
| "outputs": [], | |
| "source": [ | |
| "X = np.append(np.random.normal(100, 100, 1000), np.random.normal(300, 40, 1000))" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "execution_count": 3, | |
| "metadata": {}, | |
| "outputs": [], | |
| "source": [ | |
| "def K(x, mu=0, std=1):\n", | |
| " return 1 / (np.sqrt(2*np.pi*std)*std) * np.exp(-((x-mu)*(x-mu)) / (2*std*std))" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "execution_count": 4, | |
| "metadata": {}, | |
| "outputs": [], | |
| "source": [ | |
| "def silverman():\n", | |
| " return 1.06 * np.sqrt(X.var()) * np.power(len(X), -1/5)" | |
| ] | |
| }, | |
| { | |
| "cell_type": "code", | |
| "execution_count": 5, | |
| "metadata": {}, | |
| "outputs": [ | |
| { | |
| "data": { | |
| "application/vnd.jupyter.widget-view+json": { | |
| "model_id": "8032aefaff784bd7a73edac730856b61", | |
| "version_major": 2, | |
| "version_minor": 0 | |
| }, | |
| "text/plain": [ | |
| "interactive(children=(FloatSlider(value=29.36836731473305, description='h', max=88.10510194419915, min=-29.368…" | |
| ] | |
| }, | |
| "metadata": {}, | |
| "output_type": "display_data" | |
| } | |
| ], | |
| "source": [ | |
| "@interact\n", | |
| "def plot_edens(h=silverman()):\n", | |
| " # estimated density\n", | |
| " def f_n(x):\n", | |
| " s = 0\n", | |
| " for xi in X:\n", | |
| " s += K((x-xi)/h)\n", | |
| " return s / (len(X)*h)\n", | |
| " xvals = np.arange(np.floor(X.min()), np.ceil(X.max()))\n", | |
| " b = plt.hist(X, bins=100, density=True)\n", | |
| " a = plt.plot(xvals, f_n(xvals))" | |
| ] | |
| } | |
| ], | |
| "metadata": { | |
| "kernelspec": { | |
| "display_name": "Python 3", | |
| "language": "python", | |
| "name": "python3" | |
| }, | |
| "language_info": { | |
| "codemirror_mode": { | |
| "name": "ipython", | |
| "version": 3 | |
| }, | |
| "file_extension": ".py", | |
| "mimetype": "text/x-python", | |
| "name": "python", | |
| "nbconvert_exporter": "python", | |
| "pygments_lexer": "ipython3", | |
| "version": "3.7.3" | |
| } | |
| }, | |
| "nbformat": 4, | |
| "nbformat_minor": 2 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment