Skip to content
Advertisement

Fix parameters of Gaussian mixture model, instead of learning

Let us say I have a dataset data that I use to fit a Gaussian mixture model:

from sklearn.mixture import GaussianMixture
model = GaussianMixture(n_components=4, covariance_type="full")
fit_model = model.fit(data)

I now store the learnt covariances fit_model.covariances_, means fit_model.means_ and weights fit_model.weights_. From a different script, I want to read in the learnt parameters and define a Gaussian mixture model using them. How do I fix the parameters without executing the fit method again?

Advertisement

Answer

If you want to execute the model again, the easiest path is to save it as a pickle serializable, here’s an example:

from sklearn.mixture import GaussianMixture
import numpy as np
import pickle


X = np.random.rand(10, 2)

# Fit the model on data
model = GaussianMixture(n_components=4, covariance_type="full")
model.fit(X)

# Serialize and save the model
with open('model.pkl', 'wb') as file:
    pickle.dump(model, file)
    
# Load the model again for later use
with open('model.pkl', 'rb') as file:
    model = pickle.load(file)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement