[Python] Correct scaling of data before KDE with sklearn

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using sklearn.neighbors.KernelDensity on geospatial data. I noticed that the bandwidth estimation methods are not considering the spatial extent of the data, only the number of samples and features. The sklearn documentation or the sklearn tutorials don't seem to mention that data should be scaled.

    Hence my question: What is the an appropriate way to scale geospatial data before fitting a KDE?

    Here is a minimal example:

    import numpy as np
    from sklearn.neighbors import KernelDensity
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots

    fig = make_subplots(rows=1, cols=2)

    X_uniform = np.random.rand(100, 2)
    X_upscaled = X_uniform * 100

    for i,X in enumerate([X_uniform, X_upscaled]):
    kde = KernelDensity(kernel='gaussian', bandwidth="scott").fit(X)
    print(f"bw: {kde.bandwidth_}")

    # Create grid
    x_grid = np.linspace(X[:,0].min(), X[:,0].max(), 50)
    y_grid = np.linspace(X[:,1].min(), X[:,1].max(), 50)
    X,Y = np.meshgrid(x_grid, y_grid)
    xy = np.vstack([X.ravel(), Y.ravel()]).T

    z = np.exp(kde.score_samples(xy)).reshape(X.shape)
    fig.add_trace(go.Contour(z=z, x=x_grid, y=y_grid), row=1, col=i+1)

    fig.show()

    Continue reading...

Compartilhe esta Página