7-RNN_Classifier_example.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. # 8 - RNN Classifier example
  10. # to try tensorflow, un-comment following two lines
  11. # import os
  12. # os.environ['KERAS_BACKEND']='tensorflow'
  13. import numpy as np
  14. np.random.seed(1337) # for reproducibility
  15. from keras.datasets import mnist
  16. from keras.utils import np_utils
  17. from keras.models import Sequential
  18. from keras.layers import SimpleRNN, Activation, Dense
  19. from keras.optimizers import Adam
  20. TIME_STEPS = 28 # same as the height of the image
  21. INPUT_SIZE = 28 # same as the width of the image
  22. BATCH_SIZE = 50
  23. BATCH_INDEX = 0
  24. OUTPUT_SIZE = 10
  25. CELL_SIZE = 50
  26. LR = 0.001
  27. # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
  28. # X shape (60,000 28x28), y shape (10,000, )
  29. (X_train, y_train), (X_test, y_test) = mnist.load_data()
  30. # data pre-processing
  31. X_train = X_train.reshape(-1, 28, 28) / 255. # normalize
  32. X_test = X_test.reshape(-1, 28, 28) / 255. # normalize
  33. y_train = np_utils.to_categorical(y_train, num_classes=10)
  34. y_test = np_utils.to_categorical(y_test, num_classes=10)
  35. # build RNN model
  36. model = Sequential()
  37. # RNN cell
  38. model.add(SimpleRNN(
  39. # for batch_input_shape, if using tensorflow as the backend, we have to put None for the batch_size.
  40. # Otherwise, model.evaluate() will get error.
  41. batch_input_shape=(None, TIME_STEPS, INPUT_SIZE), # Or: input_dim=INPUT_SIZE, input_length=TIME_STEPS,
  42. output_dim=CELL_SIZE,
  43. unroll=True,
  44. ))
  45. # output layer
  46. model.add(Dense(OUTPUT_SIZE))
  47. model.add(Activation('softmax'))
  48. # optimizer
  49. adam = Adam(LR)
  50. model.compile(optimizer=adam,
  51. loss='categorical_crossentropy',
  52. metrics=['accuracy'])
  53. # training
  54. for step in range(4001):
  55. # data shape = (batch_num, steps, inputs/outputs)
  56. X_batch = X_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :, :]
  57. Y_batch = y_train[BATCH_INDEX: BATCH_INDEX+BATCH_SIZE, :]
  58. cost = model.train_on_batch(X_batch, Y_batch)
  59. BATCH_INDEX += BATCH_SIZE
  60. BATCH_INDEX = 0 if BATCH_INDEX >= X_train.shape[0] else BATCH_INDEX
  61. if step % 500 == 0:
  62. cost, accuracy = model.evaluate(X_test, y_test, batch_size=y_test.shape[0], verbose=False)
  63. print('test cost: ', cost, 'test accuracy: ', accuracy)