Skip to content
Advertisement

How to plot density estimation contours of a model with 20 features?

I am following this sample to do density estimation for the Bayesian Gaussian mixture model below:

bgmm = BayesianGaussianMixture(n_components=10, random_state=7, max_iter=5000).fit(data)

in which data (as a dataframe) includes 20 columns of numeric data.

I can simply plot the model for two features of bgmm by

x = np.linspace(-20.0, 30.0)
y = np.linspace(-20.0, 40.0)
X, Y = np.meshgrid(x, y)
XX = np.array([X.ravel(), Y.ravel()]).T
Z = -bgmm.score_samples(XX)
Z = Z.reshape(X.shape)

CS = plt.contour(
    X, Y, Z, norm=LogNorm(vmin=1.0, vmax=1000.0), levels=np.logspace(0, 3, 10)
)
CB = plt.colorbar(CS, shrink=0.8, extend="both")
plt.scatter(data[:, 0], data[:, 1], 0.8)

plt.show()

But, how can I plot all the clusters in the form of density contours?

Advertisement

Answer

I believe you need to get your data into one big two-column array before fitting, so define a new X_train that combines all ten pairs of columns into one big pair of columns.

First, convert data into an array:

data_array = data.to_numpy()

And then reshape into two columns:

X_train = np.reshape(data_array, (10*data_array.shape[0], 2))

and then call the mixture.fit method with that instead of data. Then just continue following the sample, using X_train as they do (and of course use bgmm instead of clf).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement