I have trained a single layer neural network model in python (a simple model without keras and tensorflow). How canI save it after training along with weights in python, and how to load it later?
Save Your Neural Network Model to JSONThis can be saved to a file and later loaded via the model_from_json() function that will create a new model from the JSON specification. The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.
Save Your Model with pickle Pickle is the standard way of serializing objects in Python. You can use the pickle operation to serialize your machine learning algorithms and save the serialized format to a file. Later you can load this file to deserialize your model and use it to make new predictions.
There are two formats you can use to save an entire model to disk: the TensorFlow SavedModel format, and the older Keras H5 format. The recommended format is SavedModel. It is the default when you use model. save() .
All the trainable parameters like weights and biases could be treated as either Python lists or NumPy arrays ( which is mostly preferred ).
For Python lists :
If your trainable parameters are Python lists then you can use pickle
.
You can pickle
them like this :
import pickle
# weights is a Python array
pickle.dump( weights , open( 'weights.pkl' , 'wb' ) )
You can group together several objects in a set
or list
and pickle that so you have a single file. For reading it,
weights = pickle.load( open( 'weights.pkl' , 'rb' ))
For NumPy arrays :
That makes all the code easy. A NumPy array could be saved by using np.array.save()
method.
np.save( 'weights.npy' , weights )
And load it,
weights = np.load( 'weights.npy' )
Apart from these prevalent methods like writing the weights and biases to a text file or a csv file may also work. Also, a JSON file may help.
So you write it down yourself. You need some simple steps:
numpy.save
to save the ndarray.numpy.load
to load weightsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With