Demo entry 6647800

MNIST CNN Code

   

Submitted by Thijs van der Heijden on Oct 21, 2017 at 14:26
Language: Python 3. Code size: 3.0 kB.

# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# Initialising the CNN
mnist_classifier = Sequential()

# Adding the first convolutional layer
mnist_classifier.add(Conv2D(32, (3, 3), activation = 'relu', input_shape = (28, 28, 1)))

# Adding the max pooling layer
mnist_classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding the second convolutional layer
mnist_classifier.add(Conv2D(32, (3, 3), activation='relu'))

# Adding a second max pooling layer
mnist_classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding the flattening layer
mnist_classifier.add(Flatten())

# Adding the fully connected layers (Normal ANN)
mnist_classifier.add(Dense(activation = 'relu', units = 128))
mnist_classifier.add(Dense(activation = 'softmax', units = 10))

# Compiling the CNN
mnist_classifier.compile(optimizer='Adadelta',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Pre-processing the images
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                target_size=(28, 28),
                                                batch_size=32,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                                        target_size=(28, 28),
                                                        batch_size=32,
                                                        class_mode='categorical')

mnist_classifier.fit_generator(training_set,
                    steps_per_epoch=60000,
                    epochs=5,
                    validation_data=test_set,
                    validation_steps=10000)

# Making a single prediction
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat3.jpg', target_size = (28, 28))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = mnist_classifier.predict(test_image)
if result[0][0] == 1:
    prediction = 'dog'
else:
    prediction = 'cat'
    
training_set.class_indices
# Saving the trained model
mnist_classifier.save('mnist_classifier_model+weights.h5')

# Saving model as JSON
model_json = mnist_classifier.to_json()
with open("model.json", "w") as mnistJson:
    mnistJson.write(model_json)
    
# Saving the models weights
mnist_classifier.save_weights('mnistClassifierWeights.h5')

# Show the classes
training_set.class_indices

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).