{"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-01T16:24:55.465678Z","iopub.execute_input":"2025-04-01T16:24:55.466097Z","iopub.status.idle":"2025-04-01T16:24:56.944960Z","shell.execute_reply.started":"2025-04-01T16:24:55.466054Z","shell.execute_reply":"2025-04-01T16:24:56.943653Z"}},"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-01T16:25:00.253234Z","iopub.execute_input":"2025-04-01T16:25:00.253571Z","iopub.status.idle":"2025-04-01T16:25:00.258805Z","shell.execute_reply.started":"2025-04-01T16:25:00.253546Z","shell.execute_reply":"2025-04-01T16:25:00.257243Z"}},"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-01T16:25:01.572543Z","iopub.execute_input":"2025-04-01T16:25:01.572982Z","iopub.status.idle":"2025-04-01T16:25:05.401875Z","shell.execute_reply.started":"2025-04-01T16:25:01.572951Z","shell.execute_reply":"2025-04-01T16:25:05.400600Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:25:07.251851Z","iopub.execute_input":"2025-04-01T16:25:07.252230Z","iopub.status.idle":"2025-04-01T16:25:07.285607Z","shell.execute_reply.started":"2025-04-01T16:25:07.252202Z","shell.execute_reply":"2025-04-01T16:25:07.284372Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We will work on numpy data format","metadata":{}},{"cell_type":"code","source":"data=np.array(data)\nm,n=data.shape\nnp.random.shuffle(data)\n\ndataDev=data[:1000].T\nXdev=dataDev[1:n]\nYdev=dataDev[0]\n\ndataTrain=data[1000:m].T\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-01T16:25:10.723096Z","iopub.execute_input":"2025-04-01T16:25:10.723506Z","iopub.status.idle":"2025-04-01T16:25:11.915806Z","shell.execute_reply.started":"2025-04-01T16:25:10.723478Z","shell.execute_reply":"2025-04-01T16:25:11.914327Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(m,\" and\",n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:25:14.560281Z","iopub.execute_input":"2025-04-01T16:25:14.560672Z","iopub.status.idle":"2025-04-01T16:25:14.567122Z","shell.execute_reply.started":"2025-04-01T16:25:14.560643Z","shell.execute_reply":"2025-04-01T16:25:14.565841Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(Ytrain.shape)\nprint(\"Shape of one col denoting a sample data:\",Xtrain[:,0].shape )#getting a row","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:25:17.830216Z","iopub.execute_input":"2025-04-01T16:25:17.830637Z","iopub.status.idle":"2025-04-01T16:25:17.837609Z","shell.execute_reply.started":"2025-04-01T16:25:17.830603Z","shell.execute_reply":"2025-04-01T16:25:17.836278Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def init_params():\n    W1 = np.random.randn(10, 784) * 0.01 #to make it small\n    b1 = np.zeros((10, 1))\n    W2 = np.random.randn(10, 10) * 0.01\n    b2 = np.zeros((10, 1))\n    return [W1, b1, W2, b2]\n\ndef ReLU(z):\n    return np.maximum(0,z)\n\ndef softmax(Z):\n    Z -= np.max(Z, axis=0)  # Subtract max value for numerical stability\n    expZ = np.exp(Z)  \n    return expZ / np.sum(expZ, axis=0, keepdims=True) \n\ndef one_hot(Y):\n    Y = Y.astype(int)  # Ensure integer labels\n    one_hot_Y = np.zeros((Y.max() + 1, Y.size))\n    one_hot_Y[Y, np.arange(Y.size)] = 1  # Fix indexing order\n    return one_hot_Y\n\ndef forward_propagation(w1, b1, w2, b2, X):\n    Z1 = w1.dot(X) + b1\n    A1 = ReLU(Z1)\n    Z2 = w2.dot(A1) + b2\n    A2 = softmax(Z2)\n    return Z1, A1, Z2, A2\n#returning derivative which is 1 for z>0 and 0 for z<0\ndef der_Relu(z): \n    return z>0\ndef backward_propagation(Z1, A1, Z2, A2, w1, w2, X, Y):\n    m=Y.size\n    one_hot_Y = one_hot(Y)\n    dZ2 = A2 - one_hot_Y\n    dW2 = 1 / m * dZ2.dot(A1.T)\n    db2 = 1 / m * np.sum(dZ2)\n    dZ1 = w2.T.dot(dZ2) * der_Relu(Z1)\n    dW1 = 1 / m * dZ1.dot(X.T)\n    db1 = 1 / m * np.sum(dZ1)\n    return dW1, db1, dW2, db2\n\ndef update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha):\n    W1 = W1 - alpha * dW1\n    b1 = b1 - alpha * db1    \n    W2 = W2 - alpha * dW2  \n    b2 = b2 - alpha * db2    \n    return W1, b1, W2, b2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:25:21.028337Z","iopub.execute_input":"2025-04-01T16:25:21.028688Z","iopub.status.idle":"2025-04-01T16:25:21.040545Z","shell.execute_reply.started":"2025-04-01T16:25:21.028663Z","shell.execute_reply":"2025-04-01T16:25:21.038996Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_predictions(A2):\n    return np.argmax(A2,axis=0)\n\ndef get_accuracy(predictions, Y):\n    print(predictions, Y)\n    return np.sum(predictions == Y) / Y.size\n\ndef compute_loss(A2, Y):\n    m = Y.shape[0]  # Number of examples\n    # Convert Y into integer type if needed\n    Y = Y.astype(int)\n    log_probs = -np.log(A2[Y, np.arange(m)])  # Selecting correct class probabilities\n    loss = np.sum(log_probs) / m\n    return loss\n\ndef gradient_descent(X,Y,alpha,iterations):\n    W1, b1, W2, b2 = init_params()\n    for i in range(iterations):\n        Z1, A1, Z2, A2 = forward_propagation(W1, b1, W2, b2, X)\n        dW1, db1, dW2, db2 = backward_propagation(Z1, A1, Z2, A2, W1, W2, X, Y)\n        W1, b1, W2, b2 = update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha)\n        if i % 100 == 0:\n            loss = compute_loss(A2, Y)\n            print(f\"Iteration {i}: Loss = {loss}\")\n            predictions = get_predictions(A2)\n            accuracy = get_accuracy(predictions, Y)\n            # print(\"Accuracy:\",get_accuracy(predictions, Y))\n            print(f\"Accuracy: {accuracy:.6f} and in percentage:{accuracy * 100:.2f}%\")\n    return W1, b1, W2, b2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:53:23.026016Z","iopub.execute_input":"2025-04-01T16:53:23.026369Z","iopub.status.idle":"2025-04-01T16:53:23.034952Z","shell.execute_reply.started":"2025-04-01T16:53:23.026343Z","shell.execute_reply":"2025-04-01T16:53:23.033626Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"W1, b1, W2, b2 = gradient_descent(Xtrain, Ytrain, 0.1, 601)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:53:24.885462Z","iopub.execute_input":"2025-04-01T16:53:24.885890Z","iopub.status.idle":"2025-04-01T16:54:22.771563Z","shell.execute_reply.started":"2025-04-01T16:53:24.885861Z","shell.execute_reply":"2025-04-01T16:54:22.769889Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## normalised the data and also changed the alpha to 0.1 and iterrations to 600 which is preety good\n~90% accuracy","metadata":{}},{"cell_type":"markdown","source":"---\n# lets make some predictions using dev set","metadata":{}},{"cell_type":"code","source":"def make_predictions(X, W1, b1, W2, b2):\n    _, _, _, A2 = forward_propagation(W1, b1, W2, b2, X)\n    predictions = get_predictions(A2)\n    return predictions\n\ndef test_prediction(index, W1, b1, W2, b2):\n    current_image = Xtrain[:, index, None]\n    prediction = make_predictions(Xtrain[:, index, None], W1, b1, W2, b2)\n    label = Ytrain[index]\n    print(\"Prediction: \", prediction)\n    print(\"Label: \", label)\n    \n    current_image = current_image.reshape((28, 28)) * 255\n    plt.gray()\n    plt.imshow(current_image, interpolation='nearest')\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T17:03:23.121309Z","iopub.execute_input":"2025-04-01T17:03:23.121634Z","iopub.status.idle":"2025-04-01T17:03:23.128737Z","shell.execute_reply.started":"2025-04-01T17:03:23.121611Z","shell.execute_reply":"2025-04-01T17:03:23.127247Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(5):\n    imageNum=np.random.randint(0, 41000)\n    test_prediction(imageNum, W1, b1, W2, b2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T17:25:27.964804Z","iopub.execute_input":"2025-04-01T17:25:27.965250Z","iopub.status.idle":"2025-04-01T17:25:28.793223Z","shell.execute_reply.started":"2025-04-01T17:25:27.965221Z","shell.execute_reply":"2025-04-01T17:25:28.791914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dev_predictions = make_predictions(Xdev, W1, b1, W2, b2)\ntestAcc=get_accuracy(dev_predictions, Ydev)\nprint(f\"size of Ydev is:{Ydev.shape}\")\nprint(f\"Accuracy: {testAcc:.6f} and in percentage:{testAcc * 100:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T17:18:06.250209Z","iopub.execute_input":"2025-04-01T17:18:06.250609Z","iopub.status.idle":"2025-04-01T17:18:06.264608Z","shell.execute_reply.started":"2025-04-01T17:18:06.250579Z","shell.execute_reply":"2025-04-01T17:18:06.263432Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"~90% accurace here too\n\n---\n\nbuilt a neuralk netwokr with one hidden layer consisteing of ReLU activation function and the output layer as softmax activation for probility","metadata":{}},{"cell_type":"markdown","source":"Forward prop\n\nA[0]=X\n : 784 x m\nZ[1]∼A[1]\n : 10 x m\nW[1]\n : 10 x 784 (as  W[1]A[0]∼Z[1]\n )\nB[1]\n : 10 x 1\nZ[2]∼A[2]\n : 10 x m\nW[1]\n : 10 x 10 (as  W[2]A[1]∼Z[2]\n )\nB[2]\n : 10 x 1\nBackprop\n\ndZ[2]\n : 10 x m (  A[2]\n )\ndW[2]\n : 10 x 10\ndB[2]\n : 10 x 1\ndZ[1]\n : 10 x m (  A[1]\n )\ndW[1]\n : 10 x 10\ndB[1]\n : 10 x 1","metadata":{}},{"cell_type":"markdown","source":"# Sayonara","metadata":{}}]}