{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":6799,"databundleVersionId":4225553,"sourceType":"competition"},{"sourceId":7604457,"sourceType":"datasetVersion","datasetId":4427069}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"###MNIST Image Classification\n##1D\nfrom tensorflow import keras\nfrom keras.datasets import mnist","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-15T06:35:02.43301Z","iopub.execute_input":"2024-02-15T06:35:02.433698Z","iopub.status.idle":"2024-02-15T06:35:23.070529Z","shell.execute_reply.started":"2024-02-15T06:35:02.433636Z","shell.execute_reply":"2024-02-15T06:35:23.069572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(X_train,y_train),(X_test, y_test)= mnist.load_data()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.072588Z","iopub.execute_input":"2024-02-15T06:35:23.073681Z","iopub.status.idle":"2024-02-15T06:35:23.55219Z","shell.execute_reply.started":"2024-02-15T06:35:23.073622Z","shell.execute_reply":"2024-02-15T06:35:23.55135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.553377Z","iopub.execute_input":"2024-02-15T06:35:23.553633Z","iopub.status.idle":"2024-02-15T06:35:23.5595Z","shell.execute_reply.started":"2024-02-15T06:35:23.553612Z","shell.execute_reply":"2024-02-15T06:35:23.558454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"raw","source":"To build a fully connected NN:\n1.Flatten input to 1D\n2.Normalise pixel vales\n3.One-hot encoding for categories\n4.Builing seqential model\n5.Train model","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Conv2D, MaxPool2D","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.561854Z","iopub.execute_input":"2024-02-15T06:35:23.562268Z","iopub.status.idle":"2024-02-15T06:35:23.631715Z","shell.execute_reply.started":"2024-02-15T06:35:23.562227Z","shell.execute_reply":"2024-02-15T06:35:23.630991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train.reshape(60000,784)\nX_test = X_test.reshape(10000, 784)\nX_train=X_train.astype('float32')\nX_test=X_test.astype('float32')","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.632596Z","iopub.execute_input":"2024-02-15T06:35:23.632917Z","iopub.status.idle":"2024-02-15T06:35:23.697065Z","shell.execute_reply.started":"2024-02-15T06:35:23.632886Z","shell.execute_reply":"2024-02-15T06:35:23.696047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train/=255.0 \nX_test/=255.0 ","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.698366Z","iopub.execute_input":"2024-02-15T06:35:23.699301Z","iopub.status.idle":"2024-02-15T06:35:23.721578Z","shell.execute_reply.started":"2024-02-15T06:35:23.699271Z","shell.execute_reply":"2024-02-15T06:35:23.720852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_classes=10\ny_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.722567Z","iopub.execute_input":"2024-02-15T06:35:23.722862Z","iopub.status.idle":"2024-02-15T06:35:23.730047Z","shell.execute_reply.started":"2024-02-15T06:35:23.722838Z","shell.execute_reply":"2024-02-15T06:35:23.728952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils import to_categorical\ny_train= keras.utils.to_categorical(y_train, n_classes)\ny_test=keras.utils.to_categorical(y_test, n_classes)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.731372Z","iopub.execute_input":"2024-02-15T06:35:23.731737Z","iopub.status.idle":"2024-02-15T06:35:23.957849Z","shell.execute_reply.started":"2024-02-15T06:35:23.731706Z","shell.execute_reply":"2024-02-15T06:35:23.956989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(y_train.shape, y_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.959268Z","iopub.execute_input":"2024-02-15T06:35:23.959602Z","iopub.status.idle":"2024-02-15T06:35:23.964588Z","shell.execute_reply.started":"2024-02-15T06:35:23.959574Z","shell.execute_reply":"2024-02-15T06:35:23.963463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Dense(100, input_shape=(784,), activation='relu'))\nmodel.add(Dense(10, activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:23.968062Z","iopub.execute_input":"2024-02-15T06:35:23.968749Z","iopub.status.idle":"2024-02-15T06:35:25.106962Z","shell.execute_reply.started":"2024-02-15T06:35:23.968711Z","shell.execute_reply":"2024-02-15T06:35:25.106132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:25.108151Z","iopub.execute_input":"2024-02-15T06:35:25.108474Z","iopub.status.idle":"2024-02-15T06:35:25.124356Z","shell.execute_reply.started":"2024-02-15T06:35:25.108446Z","shell.execute_reply":"2024-02-15T06:35:25.123434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\nmodel.fit(X_train, y_train, batch_size=128, epochs=10, validation_data=(X_test, y_test))\n","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:35:25.125708Z","iopub.execute_input":"2024-02-15T06:35:25.126316Z","iopub.status.idle":"2024-02-15T06:35:46.947864Z","shell.execute_reply.started":"2024-02-15T06:35:25.126283Z","shell.execute_reply":"2024-02-15T06:35:46.946832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"###CNN Model\nfrom tensorflow import keras\nfrom keras.datasets import mnist\n(X_train,y_train),(X_test, y_test)= mnist.load_data()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:26.182816Z","iopub.execute_input":"2024-02-15T06:36:26.183235Z","iopub.status.idle":"2024-02-15T06:36:26.467791Z","shell.execute_reply.started":"2024-02-15T06:36:26.183203Z","shell.execute_reply":"2024-02-15T06:36:26.466723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train.reshape(60000,28,28,1)  ##input vector of 28x28 pixels\nX_test = X_test.reshape(10000, 28,28,1)\nX_train=X_train.astype('float32')\nX_test=X_test.astype('float32')","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:26.48197Z","iopub.execute_input":"2024-02-15T06:36:26.482682Z","iopub.status.idle":"2024-02-15T06:36:26.543496Z","shell.execute_reply.started":"2024-02-15T06:36:26.482623Z","shell.execute_reply":"2024-02-15T06:36:26.542429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train/=255.0 \nX_test/=255.0 ","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:26.772109Z","iopub.execute_input":"2024-02-15T06:36:26.772462Z","iopub.status.idle":"2024-02-15T06:36:26.797902Z","shell.execute_reply.started":"2024-02-15T06:36:26.772435Z","shell.execute_reply":"2024-02-15T06:36:26.796853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_classes=10\nY_train = keras.utils.to_categorical(y_train, n_classes)\nY_test =  keras.utils.to_categorical(y_test, n_classes)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:27.282927Z","iopub.execute_input":"2024-02-15T06:36:27.28356Z","iopub.status.idle":"2024-02-15T06:36:27.289564Z","shell.execute_reply.started":"2024-02-15T06:36:27.283527Z","shell.execute_reply":"2024-02-15T06:36:27.2887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(y_train.shape,Y_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:27.712713Z","iopub.execute_input":"2024-02-15T06:36:27.71355Z","iopub.status.idle":"2024-02-15T06:36:27.718303Z","shell.execute_reply.started":"2024-02-15T06:36:27.713519Z","shell.execute_reply":"2024-02-15T06:36:27.717364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.layers import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, MaxPool2D, Activation, Dropout\n\n\n##linear stack of layers\nmodel1=Sequential()\nmodel1.add(Conv2D(25, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu', input_shape=(28,28,1)))\nmodel1.add(MaxPool2D(pool_size=(1,1))) ###downsampling\nmodel1.add(Dropout(0.1))\n\nmodel1.add(Conv2D(50, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu', input_shape=(28,28,1)))\nmodel1.add(MaxPool2D(pool_size=(2,2))) ###downsampling\nmodel1.add(Dropout(0.5))\n\nmodel1.add(Conv2D(25, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu', input_shape=(28,28,1)))\nmodel1.add(MaxPool2D(pool_size=(1,1))) ###downsampling\nmodel1.add(Dropout(0.1))\n\nmodel1.add(Flatten())\n\nmodel1.add(Dense(100, activation='relu'))\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(10, activation='softmax'))\nmodel1.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:28.152652Z","iopub.execute_input":"2024-02-15T06:36:28.153036Z","iopub.status.idle":"2024-02-15T06:36:28.270439Z","shell.execute_reply.started":"2024-02-15T06:36:28.153007Z","shell.execute_reply":"2024-02-15T06:36:28.269283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model1.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:29.797141Z","iopub.execute_input":"2024-02-15T06:36:29.797753Z","iopub.status.idle":"2024-02-15T06:36:29.833786Z","shell.execute_reply.started":"2024-02-15T06:36:29.797723Z","shell.execute_reply":"2024-02-15T06:36:29.832723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h = model1.fit(X_train, Y_train, batch_size=64, epochs=8, validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:36:39.239401Z","iopub.execute_input":"2024-02-15T06:36:39.239771Z","iopub.status.idle":"2024-02-15T06:37:22.34249Z","shell.execute_reply.started":"2024-02-15T06:36:39.239742Z","shell.execute_reply":"2024-02-15T06:37:22.341568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.plot(h.history['accuracy'])\nplt.plot(h.history['val_accuracy'])\nplt.title(\"Model accuracy\")\n\nplt.ylabel('Accuracy')\nplt.xlabel(\"Eppochs\")\n\nplt.legend(['Train', 'Validation'], loc='best')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:37:37.357486Z","iopub.execute_input":"2024-02-15T06:37:37.357867Z","iopub.status.idle":"2024-02-15T06:37:37.678973Z","shell.execute_reply.started":"2024-02-15T06:37:37.357837Z","shell.execute_reply":"2024-02-15T06:37:37.677854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loss, test_accuracy=model1.evaluate(X_test, Y_test)\nprint(test_loss, test_accuracy)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:37:42.307956Z","iopub.execute_input":"2024-02-15T06:37:42.308952Z","iopub.status.idle":"2024-02-15T06:37:43.57141Z","shell.execute_reply.started":"2024-02-15T06:37:42.308901Z","shell.execute_reply":"2024-02-15T06:37:43.570296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\nimport numpy as np\ny_pred_prob = model1.predict(X_test)\ny_pred = np.argmax(y_pred_prob, axis=1)\nreport = classification_report(y_test, y_pred)\n\nprint(report)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:37:47.277799Z","iopub.execute_input":"2024-02-15T06:37:47.278497Z","iopub.status.idle":"2024-02-15T06:37:48.911669Z","shell.execute_reply.started":"2024-02-15T06:37:47.278466Z","shell.execute_reply":"2024-02-15T06:37:48.910576Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = np.random.randint(0, len(X_test))\nimage = X_test[i]\ntrue_label = y_test[i]\ny_pred_prob = model1.predict(image.reshape(1, 28, 28, 1))\npredicted_label = np.argmax(y_pred_prob)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:33.972343Z","iopub.execute_input":"2024-02-15T06:38:33.972742Z","iopub.status.idle":"2024-02-15T06:38:34.044492Z","shell.execute_reply.started":"2024-02-15T06:38:33.972713Z","shell.execute_reply":"2024-02-15T06:38:34.043709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_names = [0,1,2,3,4,5,6,7,8,9]\nplt.imshow(image.reshape(28, 28), cmap='gray')\nplt.title(f'True Label: {class_names[true_label]}, Predicted Label: {class_names[predicted_label]}')\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:34.353387Z","iopub.execute_input":"2024-02-15T06:38:34.35378Z","iopub.status.idle":"2024-02-15T06:38:34.466469Z","shell.execute_reply.started":"2024-02-15T06:38:34.353749Z","shell.execute_reply":"2024-02-15T06:38:34.465335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"###Using Keras-tuner\nfrom tensorflow import keras\nfrom keras.datasets import mnist\n(X_train,y_train),(X_test, y_test)= mnist.load_data()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:39.862636Z","iopub.execute_input":"2024-02-15T06:38:39.863033Z","iopub.status.idle":"2024-02-15T06:38:40.130158Z","shell.execute_reply.started":"2024-02-15T06:38:39.863003Z","shell.execute_reply":"2024-02-15T06:38:40.129373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=X_train.astype('float32')\nX_test=X_test.astype('float32')\nX_train/=255.0 \nX_test/=255.0 \nn_classes=10\nY_train = keras.utils.to_categorical(y_train, n_classes)\nY_test =  keras.utils.to_categorical(y_test, n_classes)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:40.194734Z","iopub.execute_input":"2024-02-15T06:38:40.195032Z","iopub.status.idle":"2024-02-15T06:38:40.277244Z","shell.execute_reply.started":"2024-02-15T06:38:40.195006Z","shell.execute_reply":"2024-02-15T06:38:40.276375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model(hp):\n    model=keras.Sequential([\n        keras.layers.Conv2D(\n            filters=hp.Int('conv_1_filter', min_value=32, max_value=128, step=8),\n            kernel_size=hp.Choice('conv_1_kernel', values=[3,5]),\n            activation='relu',\n            input_shape=(28,28,1)\n        ),\n        \n        keras.layers.Dropout(hp.Choice('dropout_1', values=[0.1,0.5])),\n        \n        keras.layers.Conv2D(\n            filters=hp.Int('conv_2_filter', min_value=32, max_value=128, step=8),\n            kernel_size=hp.Choice('conv_2_kernel', values=[3,5]),\n            activation='relu'\n        ),\n        \n        keras.layers.Dropout(hp.Choice('dropout_2', values=[0.1,0.5])),\n        \n        keras.layers.Conv2D(\n            filters=hp.Int('conv_2_filter', min_value=32, max_value=128, step=8),\n            kernel_size=hp.Choice('conv_2_kernel', values=[3,5]),\n            activation='relu'\n        ),\n        \n        keras.layers.Dropout(hp.Choice('dropout_2', values=[0.1,0.5])),\n        \n        keras.layers.Flatten(),\n        \n        keras.layers.Dense(\n            units=hp.Int('dense_1_units',min_value=32, max_value=128, step=16),\n            activation='relu'\n        ),\n        \n        keras.layers.Dropout(hp.Choice('dropout_3', values=[0.1,0.5])),\n        \n        keras.layers.Flatten(),\n        \n        keras.layers.Dense(\n            units=hp.Int('dense_1_units',min_value=32, max_value=128, step=16),\n            activation='relu'\n        ),\n        \n        keras.layers.Dropout(hp.Choice('dropout_4', values=[0.1,0.5])),\n        \n        keras.layers.Dense(10, activation='softmax') #10 outputs        \n    ])\n    \n    \n    model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2,1e-3])),\n        loss='sparse_categorical_crossentropy',\n        metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:40.572327Z","iopub.execute_input":"2024-02-15T06:38:40.573223Z","iopub.status.idle":"2024-02-15T06:38:40.586274Z","shell.execute_reply.started":"2024-02-15T06:38:40.573189Z","shell.execute_reply":"2024-02-15T06:38:40.585057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras_tuner import RandomSearch\nfrom keras_tuner.engine.hyperparameters import HyperParameters\ntuner=RandomSearch(build_model, objective='val_accuracy', max_trials=8, directory='output', project_name='MNIST')","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:41.062516Z","iopub.execute_input":"2024-02-15T06:38:41.063468Z","iopub.status.idle":"2024-02-15T06:38:41.659341Z","shell.execute_reply.started":"2024-02-15T06:38:41.063432Z","shell.execute_reply":"2024-02-15T06:38:41.658495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:41.660835Z","iopub.execute_input":"2024-02-15T06:38:41.661153Z","iopub.status.idle":"2024-02-15T06:38:41.666213Z","shell.execute_reply.started":"2024-02-15T06:38:41.661126Z","shell.execute_reply":"2024-02-15T06:38:41.665271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tuner.search(X_train, y_train, epochs=4, validation_split=0.3)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:38:42.427353Z","iopub.execute_input":"2024-02-15T06:38:42.427759Z","iopub.status.idle":"2024-02-15T06:46:17.3623Z","shell.execute_reply.started":"2024-02-15T06:38:42.427727Z","shell.execute_reply":"2024-02-15T06:46:17.36143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nn=tuner.get_best_models(num_models=1)[0]\nnn.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:47:50.406661Z","iopub.execute_input":"2024-02-15T06:47:50.407533Z","iopub.status.idle":"2024-02-15T06:47:50.971578Z","shell.execute_reply.started":"2024-02-15T06:47:50.407501Z","shell.execute_reply":"2024-02-15T06:47:50.97061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"##nn.fit(X_train, y_train, epochs=8,validation_split=0.3, initial_epoch=4)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss,accuracy=nn.evaluate(X_test, y_test)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:47:59.132849Z","iopub.execute_input":"2024-02-15T06:47:59.13325Z","iopub.status.idle":"2024-02-15T06:48:00.64274Z","shell.execute_reply.started":"2024-02-15T06:47:59.13322Z","shell.execute_reply":"2024-02-15T06:48:00.64165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test loss: \", loss)\nprint(\"Test accuracy: \", accuracy)","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:48:03.692542Z","iopub.execute_input":"2024-02-15T06:48:03.693429Z","iopub.status.idle":"2024-02-15T06:48:03.698425Z","shell.execute_reply.started":"2024-02-15T06:48:03.693394Z","shell.execute_reply":"2024-02-15T06:48:03.697382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"##Model performance on other dataset\n\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef load_images_from_folder(folder):\n    images = []\n    for filename in os.listdir(folder):\n        img = cv2.imread(os.path.join(folder, filename))\n        if img is not None:\n            img = preprocess_image(img)\n            images.append(img)\n    return np.array(images)\n\ndef preprocess_image(img):\n    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    img = cv2.resize(gray_img, (28, 28))\n    img = img / 255.0 \n    img = 255 - img\n    return img\n\nnew_images = load_images_from_folder('/kaggle/input/images')\n\nrandom_index = np.random.randint(0, len(new_images))\nimage = new_images[random_index]\n\nimage_for_prediction = image.reshape(1, 28, 28)\n\nprediction = nn.predict(image_for_prediction)\npredicted_class = np.argmax(prediction)\n\nprint(\"Index: \", random_index)\nplt.imshow(image, cmap='gray')\nplt.title(f'Predicted Class: {predicted_class}')\nplt.axis('off')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nn.save('model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-02-15T06:48:30.666654Z","iopub.execute_input":"2024-02-15T06:48:30.667497Z","iopub.status.idle":"2024-02-15T06:48:30.735152Z","shell.execute_reply.started":"2024-02-15T06:48:30.667465Z","shell.execute_reply":"2024-02-15T06:48:30.734196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}