<jupyter_start><jupyter_text>This example uses the [sklearn.neighbors.KernelDensity](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.htmlsklearn.neighbors.KernelDensity) class to demonstrate the principles of Kernel Density Estimation in one dimension.The first plot shows one of the problems with using histograms to visualize the density of points in 1D. Intuitively, a histogram can be thought of as a scheme in which a unit “block” is stacked above each point on a regular grid. As the top two panels show, however, the choice of gridding for these blocks can lead to wildly divergent ideas about the underlying shape of the density distribution. If we instead center each block on the point it represents, we get the estimate shown in the bottom left panel. This is a kernel density estimation with a “top hat” kernel. This idea can be generalized to other kernel shapes: the bottom-right panel of the first figure shows a Gaussian kernel density estimate over the same distribution.Scikit-learn implements efficient kernel density estimation using either a Ball Tree or KD Tree structure, through the [sklearn.neighbors.KernelDensity](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.htmlsklearn.neighbors.KernelDensity) estimator. The available kernels are shown in the second figure of this example.The third figure compares kernel density estimates for a distribution of 100 samples in 1 dimension. Though this example uses 1D distributions, kernel density estimation is easily and efficiently extensible to higher dimensions as well.  Version<jupyter_code>import sklearn
sklearn.__version__<jupyter_output><empty_output><jupyter_text>Imports  This tutorial imports [norm](http://docs.scipy.org/doc/scipy-0.11.0/reference/generated/scipy.stats.norm.htmlscipy.stats.norm) and [KernelDensity](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.htmlsklearn.neighbors.KernelDensity).<jupyter_code>import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools

import numpy as np
from scipy.stats import norm
from sklearn.neighbors import KernelDensity<jupyter_output><empty_output><jupyter_text>Plot the Progression of Histograms to Kernels<jupyter_code># Plot the progression of histograms to kernels
np.random.seed(1)
N = 20
X = np.concatenate((np.random.normal(0, 1, 0.3 * N),
                    np.random.normal(5, 1, 0.7 * N)))[:, np.newaxis]
X_plot = np.linspace(-5, 10, 1000)[:, np.newaxis]
bins = 10

fig =tools.make_subplots(rows=2, cols=2,
                         subplot_titles=("Histogram", "Histogram, bins shifted",
                                          "Tophat Kernel Density", "Gaussian Kernel Density"))
# histogram 1
fig.append_trace(go.Histogram(x=X[:, 0], nbinsy=bins, 
                  marker=dict(color='#AAAAFF', 
                              line=dict(color='black', width=1))), 
                 1, 1)

# histogram 2
fig.append_trace(go.Histogram(x=X[:, 0], nbinsy=bins + 20, 
                              marker=dict(color='#AAAAFF',
                                          line=dict(color='black',
                                                    width=1))),
                              1, 2)

# tophat KDE
kde = KernelDensity(kernel='tophat', bandwidth=0.75).fit(X)
log_dens = kde.score_samples(X_plot)

fig.append_trace(go.Scatter(x=X_plot[:, 0], y=np.exp(log_dens),
                            mode='lines', fill='tozeroy',
                            line=dict(color='#AAAAFF', width=2)), 
                 2, 1)

# Gaussian KDE
kde = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(X)
log_dens = kde.score_samples(X_plot)
fig.append_trace(go.Scatter(x=X_plot[:, 0], y=np.exp(log_dens), 
                            mode='lines', fill='tozeroy',
                            line=dict(color='#AAAAFF', width=2)),
                 2, 2)

for i in map(str, range(1, 5, 2)):
        y = 'yaxis' + i
        fig['layout'][y].update(title='Normalized Density', )
        
fig['layout'].update(hovermode='closest', height=600,
                     showlegend=False)
        
py.iplot(fig)<jupyter_output>/home/diksha/anaconda2/lib/python2.7/site-packages/ipykernel/__main__.py:4: VisibleDeprecationWarning:

using a non-integer number instead of an integer will result in an error in the future

/home/diksha/anaconda2/lib/python2.7/site-packages/ipykernel/__main__.py:5: VisibleDeprecationWarning:

using a non-integer number instead of an integer will result in an error in the future<jupyter_text>Plot all available kernels<jupyter_code>X_plot = np.linspace(-6, 6, 1000)[:, None]
X_src = np.zeros((1, 1))

fig = tools.make_subplots(rows=2, cols=3, print_grid=False,
                          subplot_titles=('gaussian', 'tophat', 'epanechnikov',
                                          'exponential', 'linear', 'cosine'))

def format_func(x, loc):
    if x == 0:
        return '0'
    elif x == 1:
        return 'h'
    elif x == -1:
        return '-h'
    else:
        return '%ih' % x



for i, kernel in enumerate(['gaussian', 'tophat', 'epanechnikov',
                            'exponential', 'linear', 'cosine']):
    log_dens = KernelDensity(kernel=kernel).fit(X_src).score_samples(X_plot)
    
    trace=go.Scatter(x=X_plot[:, 0], y=np.exp(log_dens),
                     mode='lines', fill='tozeroy',
                     line=dict(color='#AAAAFF', width=2)) 
    fig.append_trace(trace, i/3+1, i%3+1)               
    
fig['layout'].update(hovermode='closest',
                     showlegend=False, height=600, 
                     title='Available Kernels')

py.iplot(fig)<jupyter_output><empty_output><jupyter_text>Plot a 1D density example<jupyter_code>N = 100
np.random.seed(1)
data = []
X = np.concatenate((np.random.normal(0, 1, 0.3 * N),
                    np.random.normal(5, 1, 0.7 * N)))[:, np.newaxis]

X_plot = np.linspace(-5, 10, 1000)[:, np.newaxis]

true_dens = (0.3 * norm(0, 1).pdf(X_plot[:, 0])
             + 0.7 * norm(5, 1).pdf(X_plot[:, 0]))


trace1 = go.Scatter(x=X_plot[:, 0], y=true_dens, 
                    mode='lines', fill='tozeroy',
                    line=dict(color='black', width=2), 
                    name='input distribution')
data.append(trace1)

for kernel in ['gaussian', 'tophat', 'epanechnikov']:
    kde = KernelDensity(kernel=kernel, bandwidth=0.5).fit(X)
    log_dens = kde.score_samples(X_plot)
    trace2 = go.Scatter(x=X_plot[:, 0], y=np.exp(log_dens),
                        mode='lines', 
                        line=dict(width=2, dash='dash'), 
                        name="kernel = '{0}'".format(kernel))
    data.append(trace2)
    
trace3 = go.Scatter(x=X[:, 0],
                    y=-0.005 - 0.01 * np.random.random(X.shape[0]), 
                    mode='markers', showlegend=False,
                    marker=dict(color='black'))  
data.append(trace3)

layout=go.Layout(annotations=[dict(x=6, y=0.38, showarrow=False,
                                   text="N={0} points".format(N)),
                                   ],
                 xaxis=dict(zeroline=False), hovermode='closest')
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)<jupyter_output><empty_output><jupyter_text>License Author:         <NAME><jupyter_code>from IPython.display import display, HTML

display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))

! pip install git+https://github.com/plotly/publisher.git --upgrade
import publisher
publisher.publish(
    'kde-1d.ipynb', 'scikit-learn/plot-kde-1d/', 'Simple 1D Kernel Density Estimation | plotly',
    ' ',
    title = 'Simple 1D Kernel Density Estimation | plotly',
    name = 'Simple 1D Kernel Density Estimation',
    has_thumbnail='true', thumbnail='thumbnail/kde.jpg', 
    language='scikit-learn', page_type='example_index',
    display_as='nearest_neighbors', order=6,
    ipynb= '~Diksha_Gabha/3477')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1282270891961336, 'fraction_numerical': 0.022023736693992414, 'mean_word_length': 2.9545234639574263, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '593951', 'license': 'CC-BY-3.0', 'n_tokens_mistral': 2763, 'n_tokens_neox': 2561, 'n_words': 595, 'path': '_posts/scikit/1D-kernel-density-estimation/kde-1d.ipynb', 'repo_name': 'bmb804/documentation', 'size': '8182'}