{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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,"isSourceIdPinned":false,"sourceType":"competition"}],"dockerImageVersionId":31153,"isInternetEnabled":false,"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)\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","trusted":true,"execution":{"iopub.status.busy":"2025-10-17T18:44:43.21619Z","iopub.execute_input":"2025-10-17T18:44:43.217247Z","iopub.status.idle":"2025-10-17T18:44:43.598186Z","shell.execute_reply.started":"2025-10-17T18:44:43.217209Z","shell.execute_reply":"2025-10-17T18:44:43.596907Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Importing the dependencies ","metadata":{}},{"cell_type":"code","source":"import torch \nimport torch.nn as nn \nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transform\nfrom torch.utils.data import Dataset , DataLoader\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tqdm.notebook as tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:00:41.492088Z","iopub.execute_input":"2025-10-17T20:00:41.492405Z","iopub.status.idle":"2025-10-17T20:00:41.708792Z","shell.execute_reply.started":"2025-10-17T20:00:41.492385Z","shell.execute_reply":"2025-10-17T20:00:41.707375Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## The Dataset Classes","metadata":{}},{"cell_type":"code","source":"class Images(Dataset):\n    \n    def __init__(self,data_csv,transform=None,is_test=False):\n        \n        self.dataframe = pd.read_csv(data_csv)\n        self.transform = transform\n        self.is_test= is_test\n    def __len__(self):\n        \n        return len(self.dataframe)\n        \n    def __getitem__(self,index):\n        item =  self.dataframe.iloc[index]\n        if self.is_test :\n            image = item.values.reshape(28,28).astype(np.uint8)\n            lable = None\n            \n        else: \n            image = item[1:].values.reshape(28,28).astype(np.uint8)\n            lable = item.iloc[0]\n\n        image = transform.ToPILImage()(image)\n        \n        if self.transform is not None :\n            image = self.transform(image)\n            \n        if self.is_test :\n            return image\n        else:\n            return image , lable\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:11.281593Z","iopub.execute_input":"2025-10-17T20:13:11.28195Z","iopub.status.idle":"2025-10-17T20:13:11.289512Z","shell.execute_reply.started":"2025-10-17T20:13:11.281927Z","shell.execute_reply":"2025-10-17T20:13:11.288558Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## DataLoaders","metadata":{}},{"cell_type":"code","source":"train_csv = \"/kaggle/input/digit-recognizer/train.csv\"\ntest_csv = \"/kaggle/input/digit-recognizer/test.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:12.801931Z","iopub.execute_input":"2025-10-17T20:13:12.802287Z","iopub.status.idle":"2025-10-17T20:13:12.807193Z","shell.execute_reply.started":"2025-10-17T20:13:12.802261Z","shell.execute_reply":"2025-10-17T20:13:12.806207Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Making a transformer","metadata":{}},{"cell_type":"code","source":"transformer = transform.Compose([\n    transform.ToTensor(),\n    transform.Normalize((0.1306),(0.3081))\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:18.627706Z","iopub.execute_input":"2025-10-17T20:13:18.628061Z","iopub.status.idle":"2025-10-17T20:13:18.633517Z","shell.execute_reply.started":"2025-10-17T20:13:18.62804Z","shell.execute_reply":"2025-10-17T20:13:18.632313Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Loading the data into the Image Class That We Created","metadata":{}},{"cell_type":"code","source":"\ntrain_data = Images(train_csv,transform=transformer,is_test=False)\ntest_data = Images(test_csv,transform=transformer,is_test=True)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:22.151357Z","iopub.execute_input":"2025-10-17T20:13:22.151664Z","iopub.status.idle":"2025-10-17T20:13:26.206668Z","shell.execute_reply.started":"2025-10-17T20:13:22.151642Z","shell.execute_reply":"2025-10-17T20:13:26.205253Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Now the DataLoader","metadata":{}},{"cell_type":"code","source":"train_dataLoader = DataLoader(dataset=train_data, batch_size = 32,shuffle = True)\ntest_dataLoader = DataLoader(dataset=test_data, batch_size = 32,shuffle = False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:28.119132Z","iopub.execute_input":"2025-10-17T20:13:28.119474Z","iopub.status.idle":"2025-10-17T20:13:28.126304Z","shell.execute_reply.started":"2025-10-17T20:13:28.119451Z","shell.execute_reply":"2025-10-17T20:13:28.125219Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Building the NN architecture","metadata":{}},{"cell_type":"code","source":"class DigitRecognizer(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.model = nn.Sequential(\n        #2nd creating a cnn\n            nn.Conv2d(1,32,(3,3)),\n            #the parameters inside the cnn represent:\n            #1.the number of channels\"we chosse ! cuz it's black and white\"ArithmeticError\n            #2.the number of filters\n            #3.the filters shape\n            nn.ReLU(),# activation function\n            nn.Conv2d(32,64,(3,3)),\n            nn.ReLU(),\n            nn.Conv2d(64,64,(3,3)),\n            nn.ReLU(),\n            nn.Flatten(), # flatten the layers\n            nn.Linear(64*(28-6)*(28-6),10)\n        )\n    def forward(self,x):\n        return self.model(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:31.195584Z","iopub.execute_input":"2025-10-17T20:13:31.195915Z","iopub.status.idle":"2025-10-17T20:13:31.202664Z","shell.execute_reply.started":"2025-10-17T20:13:31.195891Z","shell.execute_reply":"2025-10-17T20:13:31.20184Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training Loop","metadata":{}},{"cell_type":"markdown","source":"### Defining the Loss , Optimizer and the Model","metadata":{}},{"cell_type":"code","source":"model = DigitRecognizer().to(\"cpu\")\nloss_func = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(),lr=1e-4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:36.590988Z","iopub.execute_input":"2025-10-17T20:13:36.591311Z","iopub.status.idle":"2025-10-17T20:13:36.604391Z","shell.execute_reply.started":"2025-10-17T20:13:36.591289Z","shell.execute_reply":"2025-10-17T20:13:36.602723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nnum_epoch = 80\ntotal_loss = 0.0 \n\nfor epoch in range(num_epoch):\n    model.train()\n    for batch in train_dataLoader:\n        image , lable = batch\n        image , lable = image.to(\"cpu\"), lable.to(\"cpu\")\n        optimizer.zero_grad()\n        pred = model(image)\n        loss = loss_func(pred,lable)\n\n        \n        loss.backward()\n        optimizer.step()\n        total_loss += loss.item()\n    print(f'Epoch:{epoch} loss is{loss.item()}') \n    \nprint(\"Training Finished Successfuly\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:13:37.301472Z","iopub.execute_input":"2025-10-17T20:13:37.301817Z","iopub.status.idle":"2025-10-17T20:25:59.369678Z","shell.execute_reply.started":"2025-10-17T20:13:37.301747Z","shell.execute_reply":"2025-10-17T20:25:59.368169Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Evaluating the Model","metadata":{}},{"cell_type":"code","source":"model.eval()\npredictions =[]\nwith torch.no_grad():\n    for image in test_dataLoader:\n        image = image.to(\"cpu\")\n        output = model(image)\n        _, predicted = torch.max(output.data,1)\n        predictions.extend(predicted.cpu().tolist())\n\nsubmission = pd.DataFrame (\n    {\n        \"ImageID\": range(1,len(predictions)+1),\n        \"Label\": predictions\n    }\n)\n\nsubmission.to_csv(\"FiSubmit.csv\",index=False)\n\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-17T20:33:23.27471Z","iopub.execute_input":"2025-10-17T20:33:23.275746Z","iopub.status.idle":"2025-10-17T20:33:53.982606Z","shell.execute_reply.started":"2025-10-17T20:33:23.275714Z","shell.execute_reply":"2025-10-17T20:33:53.98091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}