{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30918,"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)\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-04-02T10:22:39.400504Z","iopub.execute_input":"2025-04-02T10:22:39.400894Z","iopub.status.idle":"2025-04-02T10:22:39.848073Z","shell.execute_reply.started":"2025-04-02T10:22:39.400863Z","shell.execute_reply":"2025-04-02T10:22:39.846815Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:22:41.733487Z","iopub.execute_input":"2025-04-02T10:22:41.734011Z","iopub.status.idle":"2025-04-02T10:22:41.738281Z","shell.execute_reply.started":"2025-04-02T10:22:41.733981Z","shell.execute_reply":"2025-04-02T10:22:41.737090Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:22:48.666064Z","iopub.execute_input":"2025-04-02T10:22:48.666439Z","iopub.status.idle":"2025-04-02T10:22:50.896485Z","shell.execute_reply.started":"2025-04-02T10:22:48.666412Z","shell.execute_reply":"2025-04-02T10:22:50.895176Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data=np.array(data)\nm,n=data.shape\nnp.random.shuffle(data)\ndataDev=data[:1000]\nXdev=dataDev[:,1:n]\nYdev=dataDev[:,0]\n\ndataTrain=data[1000:m]\nXtrain=dataTrain[:,1:n]\nYtrain=dataTrain[:,0]\n\n# Normalizing data\nXtrain = Xtrain / 255.0\nXdev = Xdev / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:22:53.453237Z","iopub.execute_input":"2025-04-02T10:22:53.453575Z","iopub.status.idle":"2025-04-02T10:22:54.285202Z","shell.execute_reply.started":"2025-04-02T10:22:53.453550Z","shell.execute_reply":"2025-04-02T10:22:54.284032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(Ytrain[0,],\"and\",Ytrain[-1,])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:22:56.034892Z","iopub.execute_input":"2025-04-02T10:22:56.035311Z","iopub.status.idle":"2025-04-02T10:22:56.041266Z","shell.execute_reply.started":"2025-04-02T10:22:56.035279Z","shell.execute_reply":"2025-04-02T10:22:56.040117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Shape of Xtrain is {Xtrain.shape}\")\nprint(f\"shape of Ytarin is {Ytrain.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:22:58.787087Z","iopub.execute_input":"2025-04-02T10:22:58.787471Z","iopub.status.idle":"2025-04-02T10:22:58.794042Z","shell.execute_reply.started":"2025-04-02T10:22:58.787444Z","shell.execute_reply":"2025-04-02T10:22:58.792568Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Input\ntf.random.set_seed(1234) # for consistent results\nmodel = Sequential(\n    [               \n        tf.keras.Input(shape=(784,)),\n        Dense(25,activation='relu',name='L1'),\n        Dense(15,activation='relu',name='L2'),\n        Dense(10,activation='softmax',name='L3'),\n    ], name = \"my_model\" \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:01.930414Z","iopub.execute_input":"2025-04-02T10:23:01.930782Z","iopub.status.idle":"2025-04-02T10:23:05.312694Z","shell.execute_reply.started":"2025-04-02T10:23:01.930756Z","shell.execute_reply":"2025-04-02T10:23:05.311506Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:09.751218Z","iopub.execute_input":"2025-04-02T10:23:09.751817Z","iopub.status.idle":"2025-04-02T10:23:09.772340Z","shell.execute_reply.started":"2025-04-02T10:23:09.751784Z","shell.execute_reply":"2025-04-02T10:23:09.771042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"[layer1, layer2, layer3] = model.layers","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:13.432202Z","iopub.execute_input":"2025-04-02T10:23:13.432568Z","iopub.status.idle":"2025-04-02T10:23:13.437827Z","shell.execute_reply.started":"2025-04-02T10:23:13.432541Z","shell.execute_reply":"2025-04-02T10:23:13.436400Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Examine Weights shapes\nW1,b1 = layer1.get_weights()\nW2,b2 = layer2.get_weights()\nW3,b3 = layer3.get_weights()\nprint(f\"W1 shape = {W1.shape}, b1 shape = {b1.shape}\")\nprint(f\"W2 shape = {W2.shape}, b2 shape = {b2.shape}\")\nprint(f\"W3 shape = {W3.shape}, b3 shape = {b3.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:15.836171Z","iopub.execute_input":"2025-04-02T10:23:15.836523Z","iopub.status.idle":"2025-04-02T10:23:15.852283Z","shell.execute_reply.started":"2025-04-02T10:23:15.836498Z","shell.execute_reply":"2025-04-02T10:23:15.851011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),\n     metrics=['accuracy']  # Add accuracy metric\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:18.711208Z","iopub.execute_input":"2025-04-02T10:23:18.711575Z","iopub.status.idle":"2025-04-02T10:23:18.729488Z","shell.execute_reply.started":"2025-04-02T10:23:18.711548Z","shell.execute_reply":"2025-04-02T10:23:18.728459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model.fit(\n    Xtrain,Ytrain,epochs=40\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:23:22.451647Z","iopub.execute_input":"2025-04-02T10:23:22.452024Z","iopub.status.idle":"2025-04-02T10:24:55.342561Z","shell.execute_reply.started":"2025-04-02T10:23:22.451996Z","shell.execute_reply":"2025-04-02T10:24:55.341635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_train_accuracy = history.history['accuracy'][-1]  # Get last epoch accuracy\nprint(f\"Final Training Accuracy: {final_train_accuracy * 100:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:24:59.740835Z","iopub.execute_input":"2025-04-02T10:24:59.741198Z","iopub.status.idle":"2025-04-02T10:24:59.746451Z","shell.execute_reply.started":"2025-04-02T10:24:59.741171Z","shell.execute_reply":"2025-04-02T10:24:59.745111Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Shape of Xdev is:{Xdev.shape}\")\nprint(f\"Shape of Ydev is:{Ydev.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:25:04.277293Z","iopub.execute_input":"2025-04-02T10:25:04.277637Z","iopub.status.idle":"2025-04-02T10:25:04.283171Z","shell.execute_reply.started":"2025-04-02T10:25:04.277611Z","shell.execute_reply":"2025-04-02T10:25:04.281991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(5):\n    index = np.random.randint(0,1000)  # Picks any random index from Xdev\n    prediction = model.predict(Xdev[index:index+1])  # Get model's prediction\n    # above was making five separate predictions, triggering the progress bar five times.\n    predicted_label = np.argmax(prediction)  # Get the digit with highest probability via its index\n    true_label = Ydev[index]\n    \n    print(f\"Predicted: {predicted_label}, Actual: {true_label}\")\n    plt.imshow(Xdev[index].reshape(28, 28), cmap='gray')\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:25:06.928407Z","iopub.execute_input":"2025-04-02T10:25:06.928779Z","iopub.status.idle":"2025-04-02T10:25:08.141319Z","shell.execute_reply.started":"2025-04-02T10:25:06.928752Z","shell.execute_reply":"2025-04-02T10:25:08.140430Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# other way to predict on whole and the randomly select any 5\npredictions = model.predict(Xdev)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:25:16.540373Z","iopub.execute_input":"2025-04-02T10:25:16.540770Z","iopub.status.idle":"2025-04-02T10:25:16.732821Z","shell.execute_reply.started":"2025-04-02T10:25:16.540739Z","shell.execute_reply":"2025-04-02T10:25:16.731552Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(5):\n    index = np.random.randint(0, 1000)  # Pick a random index from Xdev\n\n    predicted_label = np.argmax(predictions[index])  # Get predicted digit\n    true_label = Ydev[index]  # Get actual digit\n\n    print(f\"Predicted: {predicted_label}, Actual: {true_label}\")\n    \n    # Display the image\n    plt.imshow(Xdev[index].reshape(28, 28), cmap='gray')\n    plt.axis('off')  # Hide axes for better visualization\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:25:18.654473Z","iopub.execute_input":"2025-04-02T10:25:18.654841Z","iopub.status.idle":"2025-04-02T10:25:18.957720Z","shell.execute_reply.started":"2025-04-02T10:25:18.654814Z","shell.execute_reply":"2025-04-02T10:25:18.956466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Get predicted labels (index of max probability for each sample)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Calculate accuracy\naccuracy = np.mean(predicted_labels == Ydev) * 100\n\nprint(f\"Final Validation Accuracy: {accuracy:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-02T10:25:33.576599Z","iopub.execute_input":"2025-04-02T10:25:33.576966Z","iopub.status.idle":"2025-04-02T10:25:33.583963Z","shell.execute_reply.started":"2025-04-02T10:25:33.576940Z","shell.execute_reply":"2025-04-02T10:25:33.582655Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"---\n### So we got nearly 97% training accuracy and around 94% testing accuracy\n## Its good for a neural network\n\nArigato for seeing my work, took some while making this\nBut was worth it","metadata":{}},{"cell_type":"markdown","source":"# All thanks to Andrew Ng course, all this was made so easy with his guidance","metadata":{}}]}