How to save trained model for future use? (models that we created from scratch using numpy, etc.)

I’ve trained a model and would like to save it for use in future. As in feed the trained model some data at convenience and expect an output with out the hassle to train the model again.

Thanks in advance. :slightly_smiling_face:

What’s the question?
Assuming it is how to save the trained model for future use, here is my response :slight_smile:
Taking the example of a neural network with some hidden input and output layers, a trained model means you have identified optimum number of hidden layers, all the weight matrices and biases at each levels (W’s and b’s). Saving these numbers ie W’s, b’s, hidden layers etc should suffice.

Next time you want to make a prediction, instead of making a random initialization of weights matrices and biases in your class, initialise them with W’s and b’s obtained from trained model. You don’t have to call ‘fit’ function as you don’t have to train. SInce the model has already been initialised with best W’s and b’s you can start calling predict function in your model to do the prediction.

Hey @sanjayk,

The Question is HOW to save the model as a seperate file .

Hi @Bilal_Aamer ,
You can use pickle files to save the parameters.
Use:, "path.pth")

Here, layer is your sequence or operations, whereas path is the path to directory where you want to save the pickle file with all your parameters.

And further if you want to load the saved parameters, you just need to do:


@Ishvinder, How’d you do that?

I haven’t tried it myself, but there is a pickle module to persist information on disk.
If you have created an object of SigmoidNeuron and trained it by calling the fit method, next you can persiste the object to disk by using pickle module.
A helpful link:

1 Like
import pickle
with open('model.pkl', 'wb') as file:
    pickle.dump(clf, file)


clf = RandomForestClassifier(n_estimators=100)

You can use this method to save your model for future use.

1 Like