keras实现CNN手写字识别

分手后的思念是犯贱 2022-12-15 03:37 301阅读 0赞
  1. # to try tensorflow, un-comment following two lines
  2. # import os
  3. # os.environ['KERAS_BACKEND']='tensorflow'
  4. import numpy as np
  5. np.random.seed(1337) # for reproducibility
  6. from keras.datasets import mnist
  7. from keras.utils import np_utils
  8. from keras.models import Sequential
  9. from keras.layers import Dense, Activation, Convolution2D, MaxPooling2D, Flatten
  10. from keras.optimizers import Adam
  11. # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
  12. # training X shape (60000, 28x28), Y shape (60000, ). test X shape (10000, 28x28), Y shape (10000, )
  13. (X_train, y_train), (X_test, y_test) = mnist.load_data()
  14. # data pre-processing
  15. X_train = X_train.reshape(-1, 1,28, 28)/255.
  16. X_test = X_test.reshape(-1, 1,28, 28)/255.
  17. y_train = np_utils.to_categorical(y_train, num_classes=10)
  18. y_test = np_utils.to_categorical(y_test, num_classes=10)
  19. # Another way to build your CNN
  20. model = Sequential()
  21. # Conv layer 1 output shape (32, 28, 28)
  22. model.add(Convolution2D(
  23. batch_input_shape=(None, 1, 28, 28),
  24. filters=32,
  25. kernel_size=5,
  26. strides=1,
  27. padding='same', # Padding method
  28. data_format='channels_first',
  29. ))
  30. model.add(Activation('relu'))
  31. # Pooling layer 1 (max pooling) output shape (32, 14, 14)
  32. model.add(MaxPooling2D(
  33. pool_size=2,
  34. strides=2,
  35. padding='same', # Padding method
  36. data_format='channels_first',
  37. ))
  38. # Conv layer 2 output shape (64, 14, 14)
  39. model.add(Convolution2D(64, 5, strides=1, padding='same', data_format='channels_first'))
  40. model.add(Activation('relu'))
  41. # Pooling layer 2 (max pooling) output shape (64, 7, 7)
  42. model.add(MaxPooling2D(2, 2, 'same', data_format='channels_first'))
  43. # Fully connected layer 1 input shape (64 * 7 * 7) = (3136), output shape (1024)
  44. model.add(Flatten())
  45. model.add(Dense(1024))
  46. model.add(Activation('relu'))
  47. # Fully connected layer 2 to shape (10) for 10 classes
  48. model.add(Dense(10))
  49. model.add(Activation('softmax'))
  50. # Another way to define your optimizer
  51. adam = Adam(lr=1e-4)
  52. # We add metrics to get more results you want to see
  53. model.compile(optimizer=adam,
  54. loss='categorical_crossentropy',
  55. metrics=['accuracy'])
  56. print('Training ------------')
  57. # Another way to train the model
  58. model.fit(X_train, y_train, epochs=1, batch_size=64,)
  59. print('\nTesting ------------')
  60. # Evaluate the model with the metrics we defined earlier
  61. loss, accuracy = model.evaluate(X_test, y_test)
  62. print('\ntest loss: ', loss)
  63. print('\ntest accuracy: ', accuracy)

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读