{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport shutil\nimport tensorflow as tf\nfrom tensorflow.keras.applications.densenet import preprocess_input\nimport matplotlib.pyplot as plt \nimport tensorflow\nfrom keras.metrics import Recall,Precision\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import InputLayer, BatchNormalization, Dropout, Flatten, Dense, Activation, MaxPool2D, Conv2D, MaxPooling2D\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array","metadata":{"execution":{"iopub.status.busy":"2024-01-09T09:58:32.927611Z","iopub.execute_input":"2024-01-09T09:58:32.927981Z","iopub.status.idle":"2024-01-09T09:58:32.934511Z","shell.execute_reply.started":"2024-01-09T09:58:32.927952Z","shell.execute_reply":"2024-01-09T09:58:32.933484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"execution":{"iopub.status.busy":"2024-01-09T09:59:20.029200Z","iopub.execute_input":"2024-01-09T09:59:20.029570Z","iopub.status.idle":"2024-01-09T09:59:20.036811Z","shell.execute_reply.started":"2024-01-09T09:59:20.029544Z","shell.execute_reply":"2024-01-09T09:59:20.035823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = pd.read_csv('../input/digit-recognizer/train.csv')\ntest_dataset = pd.read_csv('../input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-01-09T09:59:58.538261Z","iopub.execute_input":"2024-01-09T09:59:58.538726Z","iopub.status.idle":"2024-01-09T10:00:04.193966Z","shell.execute_reply.started":"2024-01-09T09:59:58.538692Z","shell.execute_reply":"2024-01-09T10:00:04.193080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:00:23.503005Z","iopub.execute_input":"2024-01-09T10:00:23.503835Z","iopub.status.idle":"2024-01-09T10:00:23.529667Z","shell.execute_reply.started":"2024-01-09T10:00:23.503797Z","shell.execute_reply":"2024-01-09T10:00:23.528766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset.shape","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:00:53.111394Z","iopub.execute_input":"2024-01-09T10:00:53.111795Z","iopub.status.idle":"2024-01-09T10:00:53.118479Z","shell.execute_reply.started":"2024-01-09T10:00:53.111747Z","shell.execute_reply":"2024-01-09T10:00:53.117242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils import to_categorical\n\ntrain_labels = np.asarray(train_dataset['label'])\ntrain_labels = to_categorical(train_labels)\n\ntrain_data = train_dataset.drop('label', axis=1)\ntrain_data = np.asarray(train_data).reshape(train_data.shape[0], 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:01:41.525256Z","iopub.execute_input":"2024-01-09T10:01:41.525659Z","iopub.status.idle":"2024-01-09T10:01:41.617322Z","shell.execute_reply.started":"2024-01-09T10:01:41.525627Z","shell.execute_reply":"2024-01-09T10:01:41.616321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_images, validation_images, train_labels, validation_labels = train_test_split(train_data, train_labels, test_size=0.3, random_state=40)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:01:59.929035Z","iopub.execute_input":"2024-01-09T10:01:59.929876Z","iopub.status.idle":"2024-01-09T10:02:00.668028Z","shell.execute_reply.started":"2024-01-09T10:01:59.929841Z","shell.execute_reply":"2024-01-09T10:02:00.667194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"DATA","metadata":{}},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255, \n    rotation_range=30, \n    width_shift_range=0.2, \n    height_shift_range=0.2, \n    shear_range=0.2, \n    zoom_range=0.2, \n    horizontal_flip=False, \n    fill_mode='constant')\n\nvalidation_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:03:35.223133Z","iopub.execute_input":"2024-01-09T10:03:35.223717Z","iopub.status.idle":"2024-01-09T10:03:35.229099Z","shell.execute_reply.started":"2024-01-09T10:03:35.223680Z","shell.execute_reply":"2024-01-09T10:03:35.227965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow(train_images, train_labels, batch_size=256)\nvalidation_generator = validation_datagen.flow(validation_images, validation_labels, batch_size=128)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:03:57.632711Z","iopub.execute_input":"2024-01-09T10:03:57.633110Z","iopub.status.idle":"2024-01-09T10:03:57.698681Z","shell.execute_reply.started":"2024-01-09T10:03:57.633078Z","shell.execute_reply":"2024-01-09T10:03:57.697680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Model****","metadata":{}},{"cell_type":"code","source":"model=Sequential()\n\n# first CNN layer of a kernel size 100\nmodel.add(Conv2D(100,(3,3),input_shape=(28,28,1)))\n#Relu layer\nmodel.add(Activation('relu'))\n#MaxPooling layer\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n# second convolution layer of a kernel size 50\n\nmodel.add(Conv2D(50,(3,3)))\n#Relu layer\nmodel.add(Activation('relu'))\n#MaxPooling layer\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n#Flatten layer \nmodel.add(Flatten())\n\n# Dropout \nmodel.add(Dropout(0.3))\n\n#FC layer of 64 neurons\nmodel.add(Dense(64,activation='relu'))\n\n#Softmax layer for two categories\nmodel.add(Dense(10,activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:04:28.078119Z","iopub.execute_input":"2024-01-09T10:04:28.078985Z","iopub.status.idle":"2024-01-09T10:04:29.300913Z","shell.execute_reply.started":"2024-01-09T10:04:28.078949Z","shell.execute_reply":"2024-01-09T10:04:29.300051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Summary\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:04:42.158439Z","iopub.execute_input":"2024-01-09T10:04:42.158830Z","iopub.status.idle":"2024-01-09T10:04:42.192986Z","shell.execute_reply.started":"2024-01-09T10:04:42.158801Z","shell.execute_reply":"2024-01-09T10:04:42.192046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nfrom IPython.display import SVG, Image\nplot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)\nImage('model.png',width=400, height=200)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:04:59.062273Z","iopub.execute_input":"2024-01-09T10:04:59.063177Z","iopub.status.idle":"2024-01-09T10:04:59.351855Z","shell.execute_reply.started":"2024-01-09T10:04:59.063139Z","shell.execute_reply":"2024-01-09T10:04:59.350852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model Compile \n\nOPT    = tensorflow.keras.optimizers.Adam(lr=0.001)\n\nmodel.compile(loss='categorical_crossentropy',\n              metrics=['accuracy',Precision(),Recall()],\n              optimizer=OPT)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:05:15.044667Z","iopub.execute_input":"2024-01-09T10:05:15.045540Z","iopub.status.idle":"2024-01-09T10:05:15.071287Z","shell.execute_reply.started":"2024-01-09T10:05:15.045497Z","shell.execute_reply":"2024-01-09T10:05:15.070572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Defining Callbacks\n\nfilepath = './best_weights.hdf5'\n\nearlystopping = EarlyStopping(monitor = 'val_accuracy', \n                              mode = 'max' , \n                              patience = 25,\n                              verbose = 1)\n\ncheckpoint    = ModelCheckpoint(filepath, \n                                monitor = 'val_accuracy', \n                                mode='max', \n                                save_best_only=True, \n                                verbose = 1)\n\n\ncallback_list = [earlystopping, checkpoint]","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:05:30.134910Z","iopub.execute_input":"2024-01-09T10:05:30.135925Z","iopub.status.idle":"2024-01-09T10:05:30.141114Z","shell.execute_reply.started":"2024-01-09T10:05:30.135886Z","shell.execute_reply":"2024-01-09T10:05:30.140186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_history=model.fit(\n                        train_generator, \n                        steps_per_epoch=100, \n                        epochs=50, \n                        validation_data=validation_generator, \n                        validation_steps=50, \n                        callbacks = callback_list,\n                        verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:05:43.558342Z","iopub.execute_input":"2024-01-09T10:05:43.559207Z","iopub.status.idle":"2024-01-09T10:14:26.418020Z","shell.execute_reply.started":"2024-01-09T10:05:43.559170Z","shell.execute_reply":"2024-01-09T10:14:26.417019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"plot","metadata":{}},{"cell_type":"code","source":"plt.plot(model_history.history['accuracy'])\nplt.plot(model_history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='lower right')\nplt.show()\n\nplt.plot(model_history.history['loss'])\nplt.plot(model_history.history['val_loss'])\nplt.title('train set loss')\n\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\nplt.show()\n\nplt.plot(model_history.history['precision'])\nplt.plot(model_history.history['val_precision'])\nplt.title(' precision')\nplt.ylabel('precision')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\nplt.show()\n\n\nplt.plot(model_history.history['recall'])\nplt.plot(model_history.history['val_recall'])\nplt.title(' recall')\nplt.ylabel('recall')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:17:19.115127Z","iopub.execute_input":"2024-01-09T10:17:19.115961Z","iopub.status.idle":"2024-01-09T10:17:20.302986Z","shell.execute_reply.started":"2024-01-09T10:17:19.115926Z","shell.execute_reply":"2024-01-09T10:17:20.301999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Evaluate","metadata":{}},{"cell_type":"code","source":"loss, acc , precision,recall=model.evaluate(validation_generator)\nprint('validation Accuracy: %.3f' % acc)\nprint('validation Precision: %.3f' % precision)\nprint('validation Recall: %.3f' % recall)\nprint('validation loss: %.3f' % loss)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:17:26.445621Z","iopub.execute_input":"2024-01-09T10:17:26.446467Z","iopub.status.idle":"2024-01-09T10:17:27.522018Z","shell.execute_reply.started":"2024-01-09T10:17:26.446422Z","shell.execute_reply":"2024-01-09T10:17:27.520903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Test","metadata":{}},{"cell_type":"code","source":"test_images = np.asarray(test_dataset)\ntest_images = test_images.reshape(test_images.shape[0], 28, 28, 1)\ntest_images = test_images.astype('float32')/255","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:17:37.880982Z","iopub.execute_input":"2024-01-09T10:17:37.881818Z","iopub.status.idle":"2024-01-09T10:17:37.933917Z","shell.execute_reply.started":"2024-01-09T10:17:37.881782Z","shell.execute_reply":"2024-01-09T10:17:37.932887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_images, batch_size=128)\nimage_id = range(1, predictions.shape[0] + 1)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:17:43.713956Z","iopub.execute_input":"2024-01-09T10:17:43.714876Z","iopub.status.idle":"2024-01-09T10:17:44.748981Z","shell.execute_reply.started":"2024-01-09T10:17:43.714835Z","shell.execute_reply":"2024-01-09T10:17:44.747921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = [np.argmax(i) for i in predictions]","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:17:50.864742Z","iopub.execute_input":"2024-01-09T10:17:50.865129Z","iopub.status.idle":"2024-01-09T10:17:50.981730Z","shell.execute_reply.started":"2024-01-09T10:17:50.865098Z","shell.execute_reply":"2024-01-09T10:17:50.980666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv('../input/digit-recognizer/sample_submission.csv')\nsample.head()","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:18:01.927691Z","iopub.execute_input":"2024-01-09T10:18:01.928447Z","iopub.status.idle":"2024-01-09T10:18:01.952992Z","shell.execute_reply.started":"2024-01-09T10:18:01.928409Z","shell.execute_reply":"2024-01-09T10:18:01.952045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'ImageId': image_id, 'Label': pred})\nsubmission.to_csv('digit_recognizer_submission', index=False)\nprint('file saved!')","metadata":{"execution":{"iopub.status.busy":"2024-01-09T10:18:05.254757Z","iopub.execute_input":"2024-01-09T10:18:05.255493Z","iopub.status.idle":"2024-01-09T10:18:05.445292Z","shell.execute_reply.started":"2024-01-09T10:18:05.255461Z","shell.execute_reply":"2024-01-09T10:18:05.444257Z"},"trusted":true},"execution_count":null,"outputs":[]}]}