I created a convolutional neural network for predicting hand-written numbers using the MNIST dataset, but now I'm stuck in predicting my own image as an input to cnn, I saved the weights after training cnn and want to use this to predict my own image (NOTE: it takes my input image is 28x28)
the code:
new_mnist.py:
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--save-model", type=int, default=-1,
help="(optional) whether or not model should be saved to disk")
ap.add_argument("-l", "--load-model", type=int, default=-1,
help="(optional) whether or not pre-trained model should be loaded")
ap.add_argument("-w", "--weights", type=str,
help="(optional) path to weights file")
args = vars(ap.parse_args())
seed = 7
numpy.random.seed(seed)
print("[INFO] downloading data...")
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
print(X_test.shape[0])
X_train = X_train / 255
X_test = X_test / 255
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
print("[INFO] compiling model...")
model = LeNet.build(num_classes = num_classes,weightsPath = args["weights"] if args["load_model"] > 0 else None)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
if args["load_model"] < 0:
print("[INFO] training...")
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1, batch_size=200, verbose=2)
print("[INFO] evaluating...")
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
elif args["load_model"] > 0:
im = imread("C:\\Users\\Divyesh\\Desktop\\mnist.png")
im = im/255
pr = model.predict_classes(im)
print(pr)
if args["save_model"] > 0:
print("[INFO] dumping weights to file...")
model.save_weights(args["weights"], overwrite=True)
lenet.py:
class LeNet:
@staticmethod
def build(num_classes,weightsPath = None):
model = Sequential()
model.add(Convolution2D(30, 5, 5, border_mode='valid', input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(15, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
if weightsPath is not None:
model.load_weights(weightsPath)
return model
in new_mnist.py I called pred (im) in which im is 28x28, but after running this program I get an error like:
ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (28, 28)
HELP !!!