Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. import pandas
  2. import numpy
  3. from keras.models import Sequential
  4. from keras.layers import Dense
  5. from keras.layers import Dropout
  6. from keras.layers import Flatten
  7. from keras.layers.convolutional import Convolution2D
  8. from keras.layers.convolutional import MaxPooling2D
  9. from keras.utils import np_utils
  10. from keras import backend as K
  11. K.set_image_dim_ordering('th')
  12.  
  13. # Constants
  14. IMG_ROWS = IMG_COLUMNS = 28
  15. NUM_EPOCHS = 250        
  16. DROPOUT = 0.2
  17. BATCH_SIZE = 50
  18. SEED = 0
  19. numpy.random.seed(SEED);
  20.  
  21. # Load data
  22. train = pandas.read_csv("../input/train.csv").values
  23. test  = pandas.read_csv("../input/test.csv").values
  24.  
  25. # Data prep
  26. # Separate data into pixels (X) and class (Y)
  27. trainX = train[:, 1:].reshape(train.shape[0], 1, IMG_ROWS, IMG_COLUMNS)
  28. trainX = trainX.astype(float)
  29. testX = test.reshape(test.shape[0], 1, IMG_ROWS, IMG_COLUMNS)
  30. testX = testX.astype(float)
  31. # Normalise pixel data
  32. trainX /= 255.0
  33. testX  /= 255.0
  34. # One hot encode outputs
  35. trainY = np_utils.to_categorical(train[:,0])
  36. numClasses = trainY.shape[1]
  37.  
  38. # Build model
  39. model = Sequential()
  40. model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same',
  41.                         input_shape=(1, IMG_ROWS, IMG_COLUMNS)))
  42. model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same'))
  43. model.add(MaxPooling2D(strides=(2, 2)))
  44. model.add(Convolution2D(64, 1, 3, activation='relu', border_mode='same'))
  45. model.add(Convolution2D(64, 3, 1, activation='relu', border_mode='same'))
  46. model.add(MaxPooling2D(strides=(2, 2)))
  47. model.add(Convolution2D(128, 1, 1, activation='relu', border_mode='same'))
  48. model.add(Convolution2D(128, 1, 1, activation='relu', border_mode='same'))
  49. model.add(MaxPooling2D(strides=(2, 2)))
  50. model.add(Flatten())
  51. model.add(Dropout(0.2))
  52. model.add(Dense(256, activation='relu'))
  53. model.add(Dense(numClasses, activation='softmax'))
  54. model.summary()
  55.  
  56. # Compile model
  57. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
  58.  
  59. # Fit model
  60. model.fit(trainX, trainY, nb_epoch=NUM_EPOCHS, batch_size=BATCH_SIZE, verbose=2)
  61.  
  62. # Evaluate
  63. yPred = cnn.predict_classes(testX)
  64. print(yPred)
  65.  
  66. # Save
  67. numpy.savetxt('mnist-cnn.csv', numpy.c_[range(1,len(yPred)+1),yPred], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement