pythonparametersneural-networksaveneuralfit

How to save and load a NeuralFit model or weights?


I have evolved a neural network to learn y=x^2 using the neuralfit library, but I would like to save the model to do predictions later. I currently have:

import neuralfit
import numpy as np

# y(x) = x^2
x = np.arange(10).reshape(-1,1)
y = x**2

# Evolve model
model = neuralfit.Model(1,1)
model.compile('alpha', loss='mse', monitors=['size'])
model.evolve(x,y,epochs=1000)

# Save model
...

How would I save and load model?


Solution

  • There are two ways to do this: (1) with Neuralfit and (2) with Keras. It is best to use NeuralFit because the resulting savefile is a lot smaller (50x in this case).

    Method 1: with NeuralFit

    Based on the documentation:

    # Save a model
    model.save('model.nf')
    
    # Load a saved model
    model = neuralfit.load('model.nf')
    

    Method 2: with Keras

    Since NeuralFit allows conversion to Keras, we can convert the model to Keras and then save it using their functionality. In other words:

    # Save a model
    keras_model = model.to_keras()
    keras_model.save('model.h5')
    
    # Load a saved model
    keras_model = keras.models.load_model('model.h5')
    model = neuralfit.from_keras(keras_model)