Spaces:
Runtime error
Runtime error
# -*- coding: utf-8 -*- | |
"""HandWrittenDigitRecognition.ipynb | |
Automatically generated by Colaboratory. | |
Original file is located at | |
https://colab.research.google.com/drive/1_tPuKWVLLeOAiFbtZCBrp7fIsPNE2DTT | |
""" | |
"""# Imports""" | |
import numpy as np | |
import keras | |
from keras.models import Sequential | |
from keras.layers import Dense, Conv2D | |
from keras.datasets import mnist | |
# Gradio to build web app for presenting the ML model | |
import gradio as gr | |
"""# Loading pre-processed MNIST dataset""" | |
# mnist.load_data() returns list of tuples | |
(x_train, y_train), (x_test, y_test) = mnist.load_data() | |
# print(f"X_train Shape: {x_train.shape} | Type - {type(x_train)}") | |
# print(f"y_train Shape: {y_train.shape} | Type - {type(y_train)}") | |
# print(f"X_test Shape: {x_test.shape} | Type - {type(x_test)}") | |
# print(f"y_test Shape: {y_test.shape} | Type - {type(y_test)}") | |
"""-> Make modifications to the train and test datasets to suit the **ML model** | |
""" | |
# flatten the shapes of x_train and x_test | |
x_train = x_train.reshape(60000, 28*28) | |
x_test = x_test.reshape(10000, 28*28) | |
# TODO: Try without resizing the images and there'll be **significant difference** in accuracy when we compare both the models | |
x_train = x_train/255.0 | |
x_test = x_test/255.0 | |
"""# ML Model""" | |
# Simple Neural Network with 3 hidden layers | |
model = Sequential() | |
model.add(Dense(512, activation='relu', input_dim=784)) | |
model.add(Dense(256, activation='relu')) | |
model.add(Dense(128, activation='relu')) | |
model.add(Dense(10, activation='sigmoid')) | |
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) | |
model.fit(x_train, y_train, epochs=20, validation_split=0.3) | |
"""# Evaluation of the Model""" | |
results = model.evaluate(x_test, y_test) | |
# print(f"Accuracy: {100*(results[1])}") | |
# print(model.predict(x_test[0:1])) # returns list of lists | |
"""# Visualization using Gradio""" | |
def predict_digit(img): | |
# img is a numpy array of shape 28*28 (it is fetched by gradio by default) | |
img=img.reshape(1, 784) | |
img = img/255.0 | |
results_dict = {} | |
prediction=model.predict(img) | |
predictions = prediction[0] | |
for i in range(len(predictions)): | |
results_dict[str(i)] = float(predictions[i]) | |
return results_dict | |
# Sketchpad - Input - Image of size 28*28 (default) | |
# Note: gr.outputs.Label(num_top_classes=3) - to filter out top 3 classes | |
ui = gr.Interface(predict_digit, inputs="sketchpad", outputs=gr.outputs.Label()) | |
ui.launch(debug='True') |