6-CNN_example.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. # 6 - CNN 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 Dense, Activation, Convolution2D, MaxPooling2D, Flatten
  19. from keras.optimizers import Adam
  20. # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
  21. # training X shape (60000, 28x28), Y shape (60000, ). test X shape (10000, 28x28), Y shape (10000, )
  22. (X_train, y_train), (X_test, y_test) = mnist.load_data()
  23. # data pre-processing
  24. X_train = X_train.reshape(-1, 1,28, 28)/255.
  25. X_test = X_test.reshape(-1, 1,28, 28)/255.
  26. y_train = np_utils.to_categorical(y_train, num_classes=10)
  27. y_test = np_utils.to_categorical(y_test, num_classes=10)
  28. # Another way to build your CNN
  29. model = Sequential()
  30. # Conv layer 1 output shape (32, 28, 28)
  31. model.add(Convolution2D(
  32. batch_input_shape=(None, 1, 28, 28),
  33. filters=32,
  34. kernel_size=5,
  35. strides=1,
  36. padding='same', # Padding method
  37. data_format='channels_first',
  38. ))
  39. model.add(Activation('relu'))
  40. # Pooling layer 1 (max pooling) output shape (32, 14, 14)
  41. model.add(MaxPooling2D(
  42. pool_size=2,
  43. strides=2,
  44. padding='same', # Padding method
  45. data_format='channels_first',
  46. ))
  47. # Conv layer 2 output shape (64, 14, 14)
  48. model.add(Convolution2D(64, 5, strides=1, padding='same', data_format='channels_first'))
  49. model.add(Activation('relu'))
  50. # Pooling layer 2 (max pooling) output shape (64, 7, 7)
  51. model.add(MaxPooling2D(2, 2, 'same', data_format='channels_first'))
  52. # Fully connected layer 1 input shape (64 * 7 * 7) = (3136), output shape (1024)
  53. model.add(Flatten())
  54. model.add(Dense(1024))
  55. model.add(Activation('relu'))
  56. # Fully connected layer 2 to shape (10) for 10 classes
  57. model.add(Dense(10))
  58. model.add(Activation('softmax'))
  59. # Another way to define your optimizer
  60. adam = Adam(lr=1e-4)
  61. # We add metrics to get more results you want to see
  62. model.compile(optimizer=adam,
  63. loss='categorical_crossentropy',
  64. metrics=['accuracy'])
  65. print('Training ------------')
  66. # Another way to train the model
  67. model.fit(X_train, y_train, epochs=1, batch_size=64,)
  68. print('\nTesting ------------')
  69. # Evaluate the model with the metrics we defined earlier
  70. loss, accuracy = model.evaluate(X_test, y_test)
  71. print('\ntest loss: ', loss)
  72. print('\ntest accuracy: ', accuracy)