Dark
Dark

Reputation: 189

2d probability distribution with rbf and scipy

I have something similar to this problem respectivly the answer of this problem: RBF interpolation: LinAlgError: singular matrix https://i.sstatic.net/QpGM6.png

But I want to do the probability distribution with rbf.

My code until now:

from scipy.interpolate.rbf import Rbf  # radial basis functions
import cv2
import matplotlib.pyplot as plt
import numpy as np

x = [1, 1, 2 ,3, 4, 4, 2, 6, 7]
y = [0, 2, 5, 6, 2, 4, 1, 5, 2]

rbf_adj = Rbf(x, y, function='gaussian')

plt.figure()

# Plotting the original points.
plot3 = plt.plot(x, y, 'ko', markersize=12)  # the original points.

plt.show()

My problem is I have only coordinates of the points: x, y But what can i use for z and d?

This is my error message:

numpy.linalg.linalg.LinAlgError: Matrix is singular.

Upvotes: 2

Views: 3305

Answers (1)

xdze2
xdze2

Reputation: 4151

This is, first, a 1D example to emphasis the difference between the Radial Basis Function interpolation and the Kernel Density Estimation of a probability distribution:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

from scipy.interpolate.rbf import Rbf  # radial basis functions
from scipy.stats import gaussian_kde

coords = np.linspace(0, 2, 7)
values = np.ones_like(coords)

x_fine = np.linspace(-1, 3, 101)

rbf_interpolation = Rbf(coords, values, function='gaussian')
interpolated_y = rbf_interpolation(x_fine)

kernel_density_estimation = gaussian_kde(coords)

plt.figure()
plt.plot(coords, values, 'ko', markersize=12)
plt.plot(x_fine, interpolated_y, '-r', label='RBF Gaussian interpolation')
plt.plot(x_fine, kernel_density_estimation(x_fine), '-b', label='kernel density estimation')
plt.legend(); plt.xlabel('x')
plt.show()

kde vs rbf

And this is the 2D interpolation using Gaussian RBF for the provided data, and by setting arbitrarily the values to z=1:

from scipy.interpolate.rbf import Rbf  # radial basis functions
import matplotlib.pyplot as plt
import numpy as np

x = [1, 1, 2 ,3, 4, 4, 2, 6, 7]
y = [0, 2, 5, 6, 2, 4, 1, 5, 2]
z = [1]*len(x)

rbf_adj = Rbf(x, y, z, function='gaussian')

x_fine = np.linspace(0, 8, 81)
y_fine = np.linspace(0, 8, 82)

x_grid, y_grid = np.meshgrid(x_fine, y_fine)

z_grid = rbf_adj(x_grid.ravel(), y_grid.ravel()).reshape(x_grid.shape)

plt.pcolor(x_fine, y_fine, z_grid);
plt.plot(x, y, 'ok');
plt.xlabel('x'); plt.ylabel('y'); plt.colorbar();
plt.title('RBF Gaussian interpolation');

rbf example

Upvotes: 7

Related Questions