10-save.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. To know more or get code samples, please visit my website:
  3. https://mofanpy.com/tutorials/
  4. Or search: 莫烦Python
  5. Thank you for supporting!
  6. """
  7. # please note, all tutorial code are running under python3.5.
  8. # If you use the version like python2.7, please modify the code accordingly
  9. # 10 - save
  10. import numpy as np
  11. np.random.seed(1337) # for reproducibility
  12. from keras.models import Sequential
  13. from keras.layers import Dense
  14. from keras.models import load_model
  15. # create some data
  16. X = np.linspace(-1, 1, 200)
  17. np.random.shuffle(X) # randomize the data
  18. Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
  19. X_train, Y_train = X[:160], Y[:160] # first 160 data points
  20. X_test, Y_test = X[160:], Y[160:] # last 40 data points
  21. model = Sequential()
  22. model.add(Dense(output_dim=1, input_dim=1))
  23. model.compile(loss='mse', optimizer='sgd')
  24. for step in range(301):
  25. cost = model.train_on_batch(X_train, Y_train)
  26. # save
  27. print('test before save: ', model.predict(X_test[0:2]))
  28. model.save('my_model.h5') # HDF5 file, you have to pip3 install h5py if don't have it
  29. del model # deletes the existing model
  30. # load
  31. model = load_model('my_model.h5')
  32. print('test after load: ', model.predict(X_test[0:2]))
  33. """
  34. # save and load weights
  35. model.save_weights('my_model_weights.h5')
  36. model.load_weights('my_model_weights.h5')
  37. # save and load fresh network without trained weights
  38. from keras.models import model_from_json
  39. json_string = model.to_json()
  40. model = model_from_json(json_string)
  41. """