{"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":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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)\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\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-08-17T19:27:52.204183Z","iopub.execute_input":"2024-08-17T19:27:52.204642Z","iopub.status.idle":"2024-08-17T19:27:52.221445Z","shell.execute_reply.started":"2024-08-17T19:27:52.204607Z","shell.execute_reply":"2024-08-17T19:27:52.220157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data=pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntrain_data.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:21.594952Z","iopub.execute_input":"2024-08-17T19:25:21.595375Z","iopub.status.idle":"2024-08-17T19:25:24.867412Z","shell.execute_reply.started":"2024-08-17T19:25:21.595343Z","shell.execute_reply":"2024-08-17T19:25:24.866193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Train dimension: \",train_data.shape)\nprint(\"Test dimension: \",test_data.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:27.825727Z","iopub.execute_input":"2024-08-17T19:25:27.826178Z","iopub.status.idle":"2024-08-17T19:25:27.832408Z","shell.execute_reply.started":"2024-08-17T19:25:27.826145Z","shell.execute_reply":"2024-08-17T19:25:27.831080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.isnull().sum().sum()","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:30.074124Z","iopub.execute_input":"2024-08-17T19:25:30.074564Z","iopub.status.idle":"2024-08-17T19:25:30.110761Z","shell.execute_reply.started":"2024-08-17T19:25:30.074531Z","shell.execute_reply":"2024-08-17T19:25:30.109546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train=train_data.drop('label',axis=1)\ny_train=train_data['label']\nx_train=np.array(x_train)\ny_train=np.array(y_train)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:34.088126Z","iopub.execute_input":"2024-08-17T19:25:34.089026Z","iopub.status.idle":"2024-08-17T19:25:34.350157Z","shell.execute_reply.started":"2024-08-17T19:25:34.088987Z","shell.execute_reply":"2024-08-17T19:25:34.348914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_plot = x_train.reshape(-1, 28, 28)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:36.708756Z","iopub.execute_input":"2024-08-17T19:25:36.709579Z","iopub.status.idle":"2024-08-17T19:25:36.714743Z","shell.execute_reply.started":"2024-08-17T19:25:36.709539Z","shell.execute_reply":"2024-08-17T19:25:36.713517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(2, 2)) \nplt.imshow(train_plot[10], cmap='gray')","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:39.392509Z","iopub.execute_input":"2024-08-17T19:25:39.392966Z","iopub.status.idle":"2024-08-17T19:25:39.614950Z","shell.execute_reply.started":"2024-08-17T19:25:39.392931Z","shell.execute_reply":"2024-08-17T19:25:39.613796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample=pd.read_csv(\"/kaggle/input/digit-recognizer/sample_submission.csv\")\nsample","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:25:42.011996Z","iopub.execute_input":"2024-08-17T19:25:42.013019Z","iopub.status.idle":"2024-08-17T19:25:42.035203Z","shell.execute_reply.started":"2024-08-17T19:25:42.012979Z","shell.execute_reply":"2024-08-17T19:25:42.034077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train_data['label'].values\nx_train = train_data.drop(columns=['label']).values\n\ny_test = np.array(sample['Label'])\nx_test = np.array(test_data)\n\n# Normalize\nx_train = x_train / 255.0\nx_test = x_test / 255.0\n\nx_train = x_train.reshape(-1, 28, 28, 1)\nx_test = x_test.reshape(-1, 28, 28, 1)\n\n# Shuffle images and labels\nx_train, y_train = shuffle(x_train, y_train, random_state=42)\n\n\nprint(\"Dimensions of training label:\", y_train.shape)\nprint(\"Dimensions of training images:\", x_train.shape)\nprint(\"Dimensions of the test label:\", y_test.shape)\nprint(\"Dimensions of the test images:\", x_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:26:45.674179Z","iopub.execute_input":"2024-08-17T19:26:45.675076Z","iopub.status.idle":"2024-08-17T19:26:46.512971Z","shell.execute_reply.started":"2024-08-17T19:26:45.675038Z","shell.execute_reply":"2024-08-17T19:26:46.511714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rotation_range=10,\n    zoom_range=0.1,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    validation_split=0.2 \n)\ndatagen.fit(x_train)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:26:49.659572Z","iopub.execute_input":"2024-08-17T19:26:49.660009Z","iopub.status.idle":"2024-08-17T19:26:49.772766Z","shell.execute_reply.started":"2024-08-17T19:26:49.659975Z","shell.execute_reply":"2024-08-17T19:26:49.771510Z"},"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)\nprint(\"X_train\", X_train.shape)\nprint(\"X_val:\", X_val.shape)\nprint(\"y_train:\", y_train.shape)\nprint(\" y_val:\", y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:26:52.682186Z","iopub.execute_input":"2024-08-17T19:26:52.683243Z","iopub.status.idle":"2024-08-17T19:26:52.779330Z","shell.execute_reply.started":"2024-08-17T19:26:52.683208Z","shell.execute_reply":"2024-08-17T19:26:52.778111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = keras.Sequential([\n    keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1, )),\n    keras.layers.MaxPooling2D(pool_size=(2, 2)),\n    keras.layers.Dropout(0.25),\n    keras.layers.Flatten(),\n    keras.layers.Dense(64, activation='relu'),\n    keras.layers.Dropout(0.5),\n    keras.layers.Dense(10, activation='softmax') \n\n])\n\nmodel.compile(loss = \"sparse_categorical_crossentropy\", metrics=['accuracy'])\n\nhistory = model.fit(\n              X_train, \n              y_train, \n              epochs=100, \n              batch_size =128, \n              validation_split= 0.3,\n              verbose=0\n              )","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:27:58.181202Z","iopub.execute_input":"2024-08-17T19:27:58.181623Z","iopub.status.idle":"2024-08-17T19:38:35.089000Z","shell.execute_reply.started":"2024-08-17T19:27:58.181592Z","shell.execute_reply":"2024-08-17T19:38:35.087857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"param_grid = { \n    'n_estimators': [200, 500],\n    'max_features': ['auto', 'sqrt', 'log2'],\n    'max_depth' : [4,5,6,7,8],\n    'criterion' :['gini', 'entropy']\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CV = GridSearchCV(estimator=model, param_grid=param_grid, cv= 5)\nCV.fit(x_train, y_train)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(x_test)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Create a DataFrame for the submission file\nsubmission = pd.DataFrame({\n    \"ImageId\": np.arange(1, len(predicted_labels) + 1),\n    \"Label\": predicted_labels\n})\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:42:54.714871Z","iopub.execute_input":"2024-08-17T19:42:54.715294Z","iopub.status.idle":"2024-08-17T19:42:58.822080Z","shell.execute_reply.started":"2024-08-17T19:42:54.715262Z","shell.execute_reply":"2024-08-17T19:42:58.821085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Accuracy for Random Forest on CV data: \",accuracy_score(y_test,pred))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) \n\n    # Accuracy graph\n    ax1.plot(history.history['accuracy'], marker='o', linestyle='-')\n    ax1.plot(history.history['val_accuracy'], marker='o', linestyle='-')\n    ax1.set_title('Accuracy - Epochs', fontsize=16)\n    ax1.set_xlabel('Epochs', fontsize=14)\n    ax1.set_ylabel('Accuracy', fontsize=14, labelpad=10) \n    ax1.legend(['Train', 'Validation'], loc='lower right', fontsize=14)\n    ax1.grid(True)\n\n    # Loss graph\n    ax2.plot(history.history['loss'], marker='o', linestyle='-')\n    ax2.plot(history.history['val_loss'], marker='o', linestyle='-')\n    ax2.set_title('Loss - Epochs', fontsize=16)\n    ax2.set_xlabel('Epochs', fontsize=14)\n    ax2.set_ylabel('Loss', fontsize=14, labelpad=10)  \n    ax2.legend(['Train', 'Validation'], loc='upper right', fontsize=14, bbox_to_anchor=(1, 1))\n    ax2.grid(True)\n\n    plt.tight_layout()  \n    plt.show() ","metadata":{"execution":{"iopub.status.busy":"2024-08-17T19:41:14.855542Z","iopub.execute_input":"2024-08-17T19:41:14.856003Z","iopub.status.idle":"2024-08-17T19:41:15.544062Z","shell.execute_reply.started":"2024-08-17T19:41:14.855967Z","shell.execute_reply":"2024-08-17T19:41:15.542846Z"},"trusted":true},"execution_count":null,"outputs":[]}]}