Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using keras to load model and assign new values to its parameters

Tags:

python

keras

I am trying to use keras to store a model and then load it to retrain. My question is how do I set the learning rate to a new value when loading a model?
Here are my code:

# Save a model
model = Sequential()
model.add(Dense(64, kernel_initializer='uniform', input_shape=(10,)))
model.add(Activation('tanh'))
model.add(Activation('softmax'))
# learning rate is 0.001
sgd = optimizers.SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.fit_generator(...)
model.save()

Then load the model,

model = load_model(model)
# Change the model's parameters here. Set the learning rate to 0.01.
model.fit_generator(...)

Thank you.

like image 370
Lion Lai Avatar asked Nov 28 '17 04:11

Lion Lai


People also ask

How do I save and load weights in keras?

Save Your Neural Network Model to JSON This 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.

What is model subclassing in keras?

In Model Sub-Classing there are two most important functions __init__ and call. Basically, we will define all the tf. keras layers or custom implemented layers inside the __init__ method and call those layers based on our network design inside the call method which is used to perform a forward propagation.

What is the model compile () method used for in keras?

compile method. Configures the model for training. optimizer: String (name of optimizer) or optimizer instance.


1 Answers

I think I find the answer:

from keras import backend as K
# To get learning rate
print(K.get_value(model.optimizer.lr))
# To set learning rate
K.set_value(model.optimizer.lr, 0.001)
keras.__version__ # 2.0.2
like image 168
Lion Lai Avatar answered Oct 25 '22 02:10

Lion Lai