{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"#My first CNN related to digit recognistion\n#I am a beginner to kaggle so if you find any error please help me with them.","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:43.669691Z","iopub.execute_input":"2024-11-24T12:11:43.670043Z","iopub.status.idle":"2024-11-24T12:11:43.678554Z","shell.execute_reply.started":"2024-11-24T12:11:43.670010Z","shell.execute_reply":"2024-11-24T12:11:43.677733Z"}},"outputs":[],"execution_count":null},{"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 seaborn as sns\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","trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:43.679770Z","iopub.execute_input":"2024-11-24T12:11:43.680094Z","iopub.status.idle":"2024-11-24T12:11:43.693259Z","shell.execute_reply.started":"2024-11-24T12:11:43.680062Z","shell.execute_reply":"2024-11-24T12:11:43.692272Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test=pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ndf_test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:43.694725Z","iopub.execute_input":"2024-11-24T12:11:43.695163Z","iopub.status.idle":"2024-11-24T12:11:44.941703Z","shell.execute_reply.started":"2024-11-24T12:11:43.695117Z","shell.execute_reply":"2024-11-24T12:11:44.940329Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample=pd.read_csv(\"/kaggle/input/digit-recognizer/sample_submission.csv\")\nsample","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:44.942672Z","iopub.execute_input":"2024-11-24T12:11:44.943006Z","iopub.status.idle":"2024-11-24T12:11:44.960286Z","shell.execute_reply.started":"2024-11-24T12:11:44.942929Z","shell.execute_reply":"2024-11-24T12:11:44.959262Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:44.961498Z","iopub.execute_input":"2024-11-24T12:11:44.961860Z","iopub.status.idle":"2024-11-24T12:11:46.984503Z","shell.execute_reply.started":"2024-11-24T12:11:44.961829Z","shell.execute_reply":"2024-11-24T12:11:46.983527Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#using CNN (Convolutional Neural Networks) as they are best for image-based tasks like\n#digit recognition as they use grids.(edges, shapes, textures,etc)\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Input\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n# load and preprocess\nx = df.drop('label', axis=1).values\ny = df['label'].values\n\n\nx= x/255.0\n# Reshape x to be 4D tensor (samples, height, width, channels)\nx = x.reshape(-1, 28, 28, 1)\n\n# One-hot encode the labels\ny = to_categorical(y, 10)\n\n# First Split: 75% train, 25% test\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:46.985873Z","iopub.execute_input":"2024-11-24T12:11:46.986187Z","iopub.status.idle":"2024-11-24T12:11:47.599301Z","shell.execute_reply.started":"2024-11-24T12:11:46.986155Z","shell.execute_reply":"2024-11-24T12:11:47.598464Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build the CNN model\nmodel = Sequential([\n    Input(shape=(28, 28, 1)),  # Input layer defining the input shape\n    Conv2D(32, kernel_size=(3, 3), activation='relu'),\n    MaxPooling2D(pool_size=(2, 2)),\n    Conv2D(64, kernel_size=(3, 3), activation='relu'),\n    MaxPooling2D(pool_size=(2, 2)),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dense(10, activation='softmax')  # 10 classes (digits 0-9)\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:47.600442Z","iopub.execute_input":"2024-11-24T12:11:47.600753Z","iopub.status.idle":"2024-11-24T12:11:47.644668Z","shell.execute_reply.started":"2024-11-24T12:11:47.600724Z","shell.execute_reply":"2024-11-24T12:11:47.643813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:47.645869Z","iopub.execute_input":"2024-11-24T12:11:47.646198Z","iopub.status.idle":"2024-11-24T12:11:47.655725Z","shell.execute_reply.started":"2024-11-24T12:11:47.646166Z","shell.execute_reply":"2024-11-24T12:11:47.654822Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the model with validation data\nmodel.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:11:47.657198Z","iopub.execute_input":"2024-11-24T12:11:47.657904Z","iopub.status.idle":"2024-11-24T12:14:17.201635Z","shell.execute_reply.started":"2024-11-24T12:11:47.657845Z","shell.execute_reply":"2024-11-24T12:14:17.200637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_loss, test_accuracy = model.evaluate(x_test, y_test)\ntest_loss, test_accuracy","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:14:17.203059Z","iopub.execute_input":"2024-11-24T12:14:17.203373Z","iopub.status.idle":"2024-11-24T12:14:18.818712Z","shell.execute_reply.started":"2024-11-24T12:14:17.203343Z","shell.execute_reply":"2024-11-24T12:14:18.817746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"prediction = model.predict(x)\npredicted_labels = np.argmax(prediction,axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:14:18.819787Z","iopub.execute_input":"2024-11-24T12:14:18.820100Z","iopub.status.idle":"2024-11-24T12:14:26.138132Z","shell.execute_reply.started":"2024-11-24T12:14:18.820070Z","shell.execute_reply":"2024-11-24T12:14:26.136981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample=pd.read_csv(\"/kaggle/input/digit-recognizer/sample_submission.csv\")\n\n# Reshape x to be 4D tensor (samples, height, width, channels)\ndf_test= np.array(df_test).reshape(-1, 28, 28, 1)\n\ndf_test=df_test/255.0\ny=model.predict(df_test)\n\ny=np.argmax(y,axis=1)\n\nsample['Label'] = np.array(y)\n\nsample.to_csv(\"submission.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:14:26.139536Z","iopub.execute_input":"2024-11-24T12:14:26.139927Z","iopub.status.idle":"2024-11-24T12:14:30.835228Z","shell.execute_reply.started":"2024-11-24T12:14:26.139879Z","shell.execute_reply":"2024-11-24T12:14:30.834369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T12:14:30.836848Z","iopub.execute_input":"2024-11-24T12:14:30.837256Z","iopub.status.idle":"2024-11-24T12:14:30.846981Z","shell.execute_reply.started":"2024-11-24T12:14:30.837209Z","shell.execute_reply":"2024-11-24T12:14:30.845904Z"}},"outputs":[],"execution_count":null}]}