{"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":"gpu","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-04T14:58:59.746797Z","iopub.execute_input":"2024-02-04T14:58:59.747291Z","iopub.status.idle":"2024-02-04T14:59:00.560280Z","shell.execute_reply.started":"2024-02-04T14:58:59.747234Z","shell.execute_reply":"2024-02-04T14:59:00.559404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\nnp.random.seed(2)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:00.562047Z","iopub.execute_input":"2024-02-04T14:59:00.562415Z","iopub.status.idle":"2024-02-04T14:59:13.199823Z","shell.execute_reply.started":"2024-02-04T14:59:00.562391Z","shell.execute_reply":"2024-02-04T14:59:13.199005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:13.201065Z","iopub.execute_input":"2024-02-04T14:59:13.201624Z","iopub.status.idle":"2024-02-04T14:59:18.330647Z","shell.execute_reply.started":"2024-02-04T14:59:13.201599Z","shell.execute_reply":"2024-02-04T14:59:18.329809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.333393Z","iopub.execute_input":"2024-02-04T14:59:18.334080Z","iopub.status.idle":"2024-02-04T14:59:18.357523Z","shell.execute_reply.started":"2024-02-04T14:59:18.334044Z","shell.execute_reply":"2024-02-04T14:59:18.356719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train[\"label\"]\nx_train = train.drop(labels = [\"label\"], axis = 1)  #axis=1 means operation to be performed on the columns means columns should be dropped\ndel train","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.358464Z","iopub.execute_input":"2024-02-04T14:59:18.358693Z","iopub.status.idle":"2024-02-04T14:59:18.444115Z","shell.execute_reply.started":"2024-02-04T14:59:18.358673Z","shell.execute_reply":"2024-02-04T14:59:18.443314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.445192Z","iopub.execute_input":"2024-02-04T14:59:18.445490Z","iopub.status.idle":"2024-02-04T14:59:18.459311Z","shell.execute_reply.started":"2024-02-04T14:59:18.445466Z","shell.execute_reply":"2024-02-04T14:59:18.458347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.460442Z","iopub.execute_input":"2024-02-04T14:59:18.460793Z","iopub.status.idle":"2024-02-04T14:59:18.477511Z","shell.execute_reply.started":"2024-02-04T14:59:18.460742Z","shell.execute_reply":"2024-02-04T14:59:18.476598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.isnull().any().describe()","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.478565Z","iopub.execute_input":"2024-02-04T14:59:18.478793Z","iopub.status.idle":"2024-02-04T14:59:18.496069Z","shell.execute_reply.started":"2024-02-04T14:59:18.478773Z","shell.execute_reply":"2024-02-04T14:59:18.495205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train/255.0 # Normalizing the pixel values to lie bw -1 and 1\ntest = test/255.0","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.497090Z","iopub.execute_input":"2024-02-04T14:59:18.497352Z","iopub.status.idle":"2024-02-04T14:59:18.587295Z","shell.execute_reply.started":"2024-02-04T14:59:18.497329Z","shell.execute_reply":"2024-02-04T14:59:18.586293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.values.reshape(-1,28,28,1) \ntest = test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.590364Z","iopub.execute_input":"2024-02-04T14:59:18.590689Z","iopub.status.idle":"2024-02-04T14:59:18.595345Z","shell.execute_reply.started":"2024-02-04T14:59:18.590664Z","shell.execute_reply":"2024-02-04T14:59:18.594474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"- values.reshape(-1,28,28,1) -> reshapes the array into a 4D shape. \n\n- 28,28,1 specifies the desired shape of each image.\n\n- 28, 28, 1 indicates that each image will be reshaped to a 28x28 pixel grid with a single color channel (1 channel for grayscale images, 3 channels for RGB images).","metadata":{}},{"cell_type":"code","source":"y_train = to_categorical(y_train, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.596380Z","iopub.execute_input":"2024-02-04T14:59:18.596670Z","iopub.status.idle":"2024-02-04T14:59:18.607041Z","shell.execute_reply.started":"2024-02-04T14:59:18.596649Z","shell.execute_reply":"2024-02-04T14:59:18.606237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.2, random_state = 42)","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.608004Z","iopub.execute_input":"2024-02-04T14:59:18.608725Z","iopub.status.idle":"2024-02-04T14:59:18.990380Z","shell.execute_reply.started":"2024-02-04T14:59:18.608701Z","shell.execute_reply":"2024-02-04T14:59:18.989590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"g = plt.imshow(x_train[0][:,:,0])","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:18.991625Z","iopub.execute_input":"2024-02-04T14:59:18.992044Z","iopub.status.idle":"2024-02-04T14:59:19.187614Z","shell.execute_reply.started":"2024-02-04T14:59:18.992013Z","shell.execute_reply":"2024-02-04T14:59:19.186727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train[100]","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:19.188929Z","iopub.execute_input":"2024-02-04T14:59:19.189280Z","iopub.status.idle":"2024-02-04T14:59:19.195704Z","shell.execute_reply.started":"2024-02-04T14:59:19.189248Z","shell.execute_reply":"2024-02-04T14:59:19.194776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPool2D, Dropout\n\nmodel = Sequential() \n# this initialises Sequential model object which \n# is an empty neural network container that allows to add layers sequentially\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation = 'relu', input_shape = (28,28,1)))\n# This line adds 1st convolutional layer.\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation = 'relu'))\n\nmodel.add(MaxPool2D(pool_size = (2,2)))\n# Max Pooling reduces the spatial dimensions of the feature maps produced by convulational layers\n\nmodel.add(Dropout(0.25))\n# Dropout randomly drops a fraction of input units during training to improve generalisation and prevent overfitting\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same',activation = 'relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation = 'relu'))\n\nmodel.add(MaxPool2D(pool_size = (2,2), strides = (2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\n# transform multi-dimensional input data into a 1-D array\n\nmodel.add(Dense(256, activation = 'relu'))\n# Adds a dense layer with 256 neurons and ReLU activation function to neural network model\n\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = 'softmax'))","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:19.197091Z","iopub.execute_input":"2024-02-04T14:59:19.197453Z","iopub.status.idle":"2024-02-04T14:59:19.942569Z","shell.execute_reply.started":"2024-02-04T14:59:19.197404Z","shell.execute_reply":"2024-02-04T14:59:19.941615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-08)\n# RMSprop is Root Mean Square Propagation is an optimization algo for training neural networks\n# lr - learning rate, rho - decay rate\n# This optimizer object created will be used during the training phase to update the weights of the neural network","metadata":{"execution":{"iopub.status.busy":"2024-02-04T14:59:19.943765Z","iopub.execute_input":"2024-02-04T14:59:19.944048Z","iopub.status.idle":"2024-02-04T14:59:19.951290Z","shell.execute_reply.started":"2024-02-04T14:59:19.944024Z","shell.execute_reply":"2024-02-04T14:59:19.950472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n# loss measures the difference b/w predicted probability distribution and true probability distribution of the classes \n# accuracy metric calculates the proportion of correct predictions made by model on training data","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:07:34.483695Z","iopub.execute_input":"2024-02-04T15:07:34.484059Z","iopub.status.idle":"2024-02-04T15:07:34.501074Z","shell.execute_reply.started":"2024-02-04T15:07:34.484030Z","shell.execute_reply":"2024-02-04T15:07:34.500188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_acc',\n                                           patience = 3,\n                                           verbose  = 1,\n                                           factor = 0.5,\n                                           min_lr = 0.00001)\n\n# The ReduceLROnPlateau callback is useful for dynamically adjusting the learning rate during training, which can help improve convergence and prevent the model from getting stuck in local minima.","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:10:01.845963Z","iopub.execute_input":"2024-02-04T15:10:01.846664Z","iopub.status.idle":"2024-02-04T15:10:01.851281Z","shell.execute_reply.started":"2024-02-04T15:10:01.846634Z","shell.execute_reply":"2024-02-04T15:10:01.850368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator( featurewise_center = False, \n                             samplewise_center = False, \n                             samplewise_std_normalization = False,\n                            featurewise_std_normalization = False,\n                            zca_whitening = False,\n                            rotation_range = 10,\n                            width_shift_range = 0.1,\n                            height_shift_range = 0.1,\n                            horizontal_flip = False,\n                            vertical_flip = False)\ndatagen.fit(x_train)","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:10:56.272961Z","iopub.execute_input":"2024-02-04T15:10:56.273766Z","iopub.status.idle":"2024-02-04T15:10:56.359600Z","shell.execute_reply.started":"2024-02-04T15:10:56.273736Z","shell.execute_reply":"2024-02-04T15:10:56.358786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(datagen.flow(x_train, y_train, batch_size = 86),\n                              epochs = 1,\n                             validation_data = (x_val, y_val),\n                              verbose = 2,\n                              steps_per_epoch = x_train.shape[0],\n                             callbacks = [learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:11:18.559153Z","iopub.execute_input":"2024-02-04T15:11:18.559801Z","iopub.status.idle":"2024-02-04T15:11:34.713240Z","shell.execute_reply.started":"2024-02-04T15:11:18.559770Z","shell.execute_reply":"2024-02-04T15:11:34.712466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.predict(test)\n\nresults = np.argmax(results, axis = 1)\n\nresults = pd.Series(results, name = \"Label\")","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:11:46.554712Z","iopub.execute_input":"2024-02-04T15:11:46.555477Z","iopub.status.idle":"2024-02-04T15:11:48.919833Z","shell.execute_reply.started":"2024-02-04T15:11:46.555443Z","shell.execute_reply":"2024-02-04T15:11:48.918966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001), name = \"ImageId\"), results], axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_dataset.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2024-02-04T15:11:54.360598Z","iopub.execute_input":"2024-02-04T15:11:54.361303Z","iopub.status.idle":"2024-02-04T15:11:54.401098Z","shell.execute_reply.started":"2024-02-04T15:11:54.361266Z","shell.execute_reply":"2024-02-04T15:11:54.400210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}