FAQ

How can I run Keras on GPU

Kashgari will use GPU by default if available, but you need to setup the Tensorflow GPU environment first. You can check gpu status using the code below:

  1. import tensorflow as tf
  2. print(tf.test.is_gpu_available())

Here is the official document of TensorFlow-GPU

How to save and resume training with ModelCheckpoint callback

You can use tf.keras.callbacks.ModelCheckpoint for saving model during training.

  1. from tensorflow.python.keras.callbacks import ModelCheckpoint
  2. filepath = "saved-model-{epoch:02d}-{acc:.2f}.hdf5"
  3. checkpoint_callback = ModelCheckpoint(filepath,
  4. monitor = 'acc',
  5. verbose = 1)
  6. model = CNN_GRU_Model()
  7. model.fit(train_x,
  8. train_y,
  9. valid_x,
  10. valid_y,
  11. callbacks=[checkpoint_callback])

ModelCheckpoint will save models struct and weights to target file, but we need token dict and label dict to fully restore the model, so we have to save model using model.save() function.

So, the full solution will be like this.

  1. from tensorflow.python.keras.callbacks import ModelCheckpoint
  2. filepath = "saved-model-{epoch:02d}-{acc:.2f}.hdf5"
  3. checkpoint_callback = ModelCheckpoint(filepath,
  4. monitor = 'acc',
  5. verbose = 1)
  6. model = CNN_GRU_Model()
  7. # This function will build token dict, label dict and model struct.
  8. model.build_model(train_x, train_y, valid_x, valid_y)
  9. # Save full model info and initial weights to the full_model folder.
  10. model.save('full_model')
  11. # Start Training
  12. model.fit(train_x,
  13. train_y,
  14. valid_x,
  15. valid_y,
  16. callbacks=[checkpoint_callback])
  17. # Load Model
  18. from kashgari.utils import load_model
  19. # We only need model struct and dicts
  20. new_model = load_model('full_model', load_weights=False)
  21. # Load weights from ModelCheckpoint
  22. new_model.tf_model.load_weights('saved-model-05-0.96.hdf5')
  23. # Resume Training
  24. # Only need to set {'initial_epoch': 5} when you wish to start new epoch from 6
  25. # Otherwise epoch will start from 1
  26. model.fit(train_x,
  27. train_y,
  28. valid_x,
  29. valid_y,
  30. callbacks=[checkpoint_callback],
  31. epochs=10,
  32. fit_kwargs={'initial_epoch': 5})