1

Handwriting recognition problem with CNN. There is a requirement: from 10000 test images, save 1000 images (.png or .jpg)accurate classified each folder of 100 images (0 -> 9). How do I do? i need an instruction about code. thanks! code :

    import keras
    from keras.datasets import mnist 
    from keras.layers import Dense, Activation, Flatten, Conv2D, 
    MaxPooling2D
    from keras.models import Sequential
    from keras.utils import to_categorical
    import numpy as np
    import matplotlib.pyplot as plt

    (train_X,train_Y), (test_X,test_Y) = mnist.load_data()

    train_X = train_X.reshape(-1, 28,28, 1)
    test_X = test_X.reshape(-1, 28,28, 1)

    train_X = train_X.astype('float32')
    test_X = test_X.astype('float32')
    test_X = test_X / 255
    train_Y_one_hot = to_categorical(train_Y)
    test_Y_one_hot = to_categorical(test_Y)

    model = Sequential()

    model.add(Conv2D(64, (3,3), input_shape=(28, 28, 1)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(64, (3,3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Flatten())
    model.add(Dense(64))

    model.add(Dense(10))
    model.add(Activation('softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy, 
    optimizer=keras.optimizers.Adam(),metrics=['accuracy'])

    model.fit(train_X, train_Y_one_hot, batch_size=64, epochs=1)

    test_loss, test_acc = model.evaluate(test_X, test_Y_one_hot)
    print('Test loss', test_loss)
    print('Test accuracy', test_acc)
    model.save('123.model')
    predictions = model.predict(test_X)
    print(np.argmax(np.round(predictions[235])))

    plt.imshow(test_X[235].reshape(28, 28), cmap = 'Greys_r')
    plt.show()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jhonny
  • 11
  • 2

1 Answers1

0

Complete Code for Saving the Correctly Classified Test Images in the respective folders of their Labels
(0 to 9), 100 images in each folder is mentioned below:

import keras
from keras.datasets import mnist 
from keras.layers import Dense, Activation, Flatten, Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt

(train_X,train_Y), (test_X,test_Y) = mnist.load_data()

train_X = train_X.reshape(-1, 28,28, 1)
test_X = test_X.reshape(-1, 28,28, 1)

train_X = train_X.astype('float32')
train_X = train_X/255
test_X = test_X.astype('float32')
test_X = test_X / 255
#train_Y_one_hot = to_categorical(train_Y)
#test_Y_one_hot = to_categorical(test_Y)

model = Sequential()

model.add(Conv2D(64, (3,3), input_shape=(28, 28, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(10))
model.add(Activation('softmax'))

model.compile(loss=keras.losses.sparse_categorical_crossentropy, 
optimizer=keras.optimizers.Adam(),metrics=['accuracy'])

#model.fit(train_X, train_Y_one_hot, batch_size=64, epochs=1)
model.fit(train_X, train_Y, batch_size=64, epochs=1)

#test_loss, test_acc = model.evaluate(test_X, test_Y_one_hot)
test_loss, test_acc = model.evaluate(test_X, test_Y)
print('Test loss', test_loss)
print('Test accuracy', test_acc)

predictions = model.predict(test_X)

#****Actual Code which you need is mentioned below

import matplotlib
import matplotlib.pyplot as plt
import os

def save_fig(fig_id, Label):
    path = os.path.join('MNIST_Images', Label, fig_id + "." + "png")    
    plt.tight_layout()
    plt.savefig(path, format="png", dpi=300)
    plt.close()

%matplotlib agg 
%matplotlib agg #These 2 lines are required to prohibit Graph being displayed in Jupyter Notebook. You can comment these if you are using other IDE

No_Of_Rows = predictions.shape[0]

Count_Dict = {}
for i in range(10):
    key = 'Count_' + str(i)
    Count_Dict[key] = 0

for Each_Row in range(No_Of_Rows):
    if np.argmax(predictions[Each_Row]) == test_Y[Each_Row]:
        Label = str(test_Y[Each_Row])
        Count_Dict['Count_' + Label] = Count_Dict['Count_' + Label] + 1
        Count_Of_Label = Count_Dict['Count_' + Label]
        if Count_Of_Label <= 100:
            plt.imshow(test_X[Each_Row].reshape(28, 28), cmap = 'Greys_r')
            plt.show()
            save_fig(str(Count_Of_Label), Label)

I've commented the below lines of code which are not required, as the Labels are already in Numeric Format.

train_Y_one_hot = to_categorical(train_Y)
test_Y_one_hot = to_categorical(test_Y)

Also, I've replaced categorical_crossentropy with sparse_categorical_crossentropy in model.compile, as we are not Encoding the Variables.

  • please, don't post text information as a picture, especially when it can be easily typed in, and does not have any particular need to be posted as a picture. – lenik Jan 02 '20 at 15:37
  • Removed the picture. Thank you for the feedback. –  Jan 07 '20 at 06:44