{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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":"2023-05-24T12:08:49.601622Z","iopub.execute_input":"2023-05-24T12:08:49.602205Z","iopub.status.idle":"2023-05-24T12:08:49.631842Z","shell.execute_reply.started":"2023-05-24T12:08:49.602167Z","shell.execute_reply":"2023-05-24T12:08:49.630842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:08:49.634283Z","iopub.execute_input":"2023-05-24T12:08:49.634630Z","iopub.status.idle":"2023-05-24T12:08:55.639935Z","shell.execute_reply.started":"2023-05-24T12:08:49.634602Z","shell.execute_reply":"2023-05-24T12:08:55.638802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nimport sklearn","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:08:55.641485Z","iopub.execute_input":"2023-05-24T12:08:55.641892Z","iopub.status.idle":"2023-05-24T12:08:56.114893Z","shell.execute_reply.started":"2023-05-24T12:08:55.641854Z","shell.execute_reply":"2023-05-24T12:08:56.113745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.rc('font', size=14)\nplt.rc('axes', labelsize=14, titlesize=14)\nplt.rc('legend', fontsize=14)\nplt.rc('xtick', labelsize=10)\nplt.rc('ytick', labelsize=10)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:30.705781Z","iopub.execute_input":"2023-05-24T12:09:30.706166Z","iopub.status.idle":"2023-05-24T12:09:30.712286Z","shell.execute_reply.started":"2023-05-24T12:09:30.706135Z","shell.execute_reply":"2023-05-24T12:09:30.711171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:31.383702Z","iopub.execute_input":"2023-05-24T12:09:31.384306Z","iopub.status.idle":"2023-05-24T12:09:31.418331Z","shell.execute_reply.started":"2023-05-24T12:09:31.384268Z","shell.execute_reply":"2023-05-24T12:09:31.417402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#null_sum = train_df.isnull().sum()\n#for column, sum_ in null_sum.iteritems():\n#    print(f\"Null values in {column}: {sum_}\")","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:32.183036Z","iopub.execute_input":"2023-05-24T12:09:32.183636Z","iopub.status.idle":"2023-05-24T12:09:32.188103Z","shell.execute_reply.started":"2023-05-24T12:09:32.183604Z","shell.execute_reply":"2023-05-24T12:09:32.187089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx=train_df.drop('label', axis=1)\ny=train_df['label']\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, shuffle=True, random_state=44)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:32.924975Z","iopub.execute_input":"2023-05-24T12:09:32.925382Z","iopub.status.idle":"2023-05-24T12:09:33.418201Z","shell.execute_reply.started":"2023-05-24T12:09:32.925335Z","shell.execute_reply":"2023-05-24T12:09:33.417142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:33.467549Z","iopub.execute_input":"2023-05-24T12:09:33.468156Z","iopub.status.idle":"2023-05-24T12:09:33.474827Z","shell.execute_reply.started":"2023-05-24T12:09:33.468122Z","shell.execute_reply":"2023-05-24T12:09:33.473676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:33.858076Z","iopub.execute_input":"2023-05-24T12:09:33.858444Z","iopub.status.idle":"2023-05-24T12:09:33.864081Z","shell.execute_reply.started":"2023-05-24T12:09:33.858411Z","shell.execute_reply":"2023-05-24T12:09:33.863023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nimport numpy as np\n\n# Assuming you have the following variables defined:\n# x_train, y_train, x_test, y_test, test_df (pandas DataFrame objects)\n\nx_train = x_train.to_numpy().reshape((-1, 28, 28, 1))\nx_test = x_test.to_numpy().reshape((-1, 28, 28, 1))\n\ny_train = to_categorical(y_train.to_numpy())\ny_test = to_categorical(y_test.to_numpy())\n\n# Define the CNN model architecture\nmodel = tf.keras.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    layers.MaxPooling2D((2, 2)),\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D((2, 2)),\n    layers.Flatten(),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Create image data generator for data augmentation\ntrain_datagen = ImageDataGenerator(rescale=1./255, rotation_range=10, width_shift_range=0.1,\n                                   height_shift_range=0.1, shear_range=0.2, zoom_range=0.2)\ntrain_generator = train_datagen.flow(x_train, y_train, batch_size=32)\n\n# Train the model\nmodel.fit(train_generator, epochs=6)\n\n# Make predictions on test data\ny_pred = model.predict(x_test)\ny_pred_labels = np.argmax(y_pred, axis=1)\n\n# Calculate accuracy\naccuracy = np.mean(y_pred_labels == np.argmax(y_test, axis=1))\nprint(\"Accuracy: {:.2%}\".format(accuracy))\n\n# Prepare the test dataset (test_df) and make predictions\ntest_df_array = test_df.to_numpy().reshape((-1, 28, 28, 1))\npredictions = model.predict(test_df_array)\npred_labels = np.argmax(predictions, axis=1)\n\n# Print the predicted labels\nprint(\"Predicted labels:\", pred_labels)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:09:34.784515Z","iopub.execute_input":"2023-05-24T12:09:34.784857Z","iopub.status.idle":"2023-05-24T12:13:17.255488Z","shell.execute_reply.started":"2023-05-24T12:09:34.784830Z","shell.execute_reply":"2023-05-24T12:13:17.254448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test_preds = model.predict(test_df)\nsample_submission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsample_submission['Label'] = pred_labels\n\nsample_submission.to_csv('submission.csv',index=False)\n#sample_submission.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-24T12:14:27.334989Z","iopub.execute_input":"2023-05-24T12:14:27.335407Z","iopub.status.idle":"2023-05-24T12:14:27.395227Z","shell.execute_reply.started":"2023-05-24T12:14:27.335362Z","shell.execute_reply":"2023-05-24T12:14:27.393871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from IPython.display import FileLink\n\n#submission_file = 'submission.csv'  # Replace with the actual file name\n\n# Create a download link for the submission file\n#FileLink(submission_file)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}