{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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,"sourceType":"competition"}],"dockerImageVersionId":30646,"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)\nimport matplotlib.pyplot as plt\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\nimport random\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":"2024-02-25T09:14:00.249945Z","iopub.execute_input":"2024-02-25T09:14:00.250345Z","iopub.status.idle":"2024-02-25T09:14:00.259618Z","shell.execute_reply.started":"2024-02-25T09:14:00.250317Z","shell.execute_reply":"2024-02-25T09:14:00.258482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:07.935034Z","iopub.execute_input":"2024-02-25T09:11:07.936075Z","iopub.status.idle":"2024-02-25T09:11:12.116804Z","shell.execute_reply.started":"2024-02-25T09:11:07.936046Z","shell.execute_reply":"2024-02-25T09:11:12.115764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()\ndata","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:12.117977Z","iopub.execute_input":"2024-02-25T09:11:12.118946Z","iopub.status.idle":"2024-02-25T09:11:12.155936Z","shell.execute_reply.started":"2024-02-25T09:11:12.118917Z","shell.execute_reply":"2024-02-25T09:11:12.154788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = data[0:2]\nsample","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:12.158389Z","iopub.execute_input":"2024-02-25T09:11:12.158780Z","iopub.status.idle":"2024-02-25T09:11:12.176198Z","shell.execute_reply.started":"2024-02-25T09:11:12.158751Z","shell.execute_reply":"2024-02-25T09:11:12.175145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = sample.T\nsample[1:data.shape[1]]","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:12.177565Z","iopub.execute_input":"2024-02-25T09:11:12.178213Z","iopub.status.idle":"2024-02-25T09:11:12.198263Z","shell.execute_reply.started":"2024-02-25T09:11:12.178184Z","shell.execute_reply":"2024-02-25T09:11:12.196911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = np.array(data)\nm, n = data.shape\n# m is num of rows (=42K) which is the number of images\n# n is num of features + 1(label attribute)\n\nnp.random.shuffle(data)\n\n# There always might be overfitting. so you want to cross-validate your model against some small portion of the training data\n# This data is called the dev dataset\ndata_dev = data[0: 1000].T\nY_dev = data_dev[0] # The label\nX_dev = data_dev[1:n]\nX_dev = X_dev/255.\n\ndata_train = data[1000:m].T\nY_train = data_train[0] # just the label for all the diff images. Dimensions are 1xm\nX_train = data_train[1:n]\nX_train = X_train / 255.\n# X_train is basically the stuff without the label attribute but all columns are now the rows and the different images are represented as columns now\n","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:12.199836Z","iopub.execute_input":"2024-02-25T09:11:12.200440Z","iopub.status.idle":"2024-02-25T09:11:13.037975Z","shell.execute_reply.started":"2024-02-25T09:11:12.200408Z","shell.execute_reply":"2024-02-25T09:11:13.037004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Array of all the labels\nY_train","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:13.039190Z","iopub.execute_input":"2024-02-25T09:11:13.039701Z","iopub.status.idle":"2024-02-25T09:11:13.046901Z","shell.execute_reply.started":"2024-02-25T09:11:13.039673Z","shell.execute_reply":"2024-02-25T09:11:13.045665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# First column of X_train: essentially the pixel values of the first image\nX_train[:, 0] ","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:13.048162Z","iopub.execute_input":"2024-02-25T09:11:13.048540Z","iopub.status.idle":"2024-02-25T09:11:13.065268Z","shell.execute_reply.started":"2024-02-25T09:11:13.048516Z","shell.execute_reply":"2024-02-25T09:11:13.064459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Equations:\n**1. Z<sup>[1]</sup><sub>10xm</sub> = W<sup>[1]</sup><sub>10x784</sub>  X<sub>784xm</sub> + b<sup>[1]</sup><sub>10xm => 10xm</sub>**\n\n**2. A<sup>[1]</sup><sub>10xm</sub> = g(Z<sup>[1]</sup>) = ReLU(Z<sup>[1]</sup><sub>10xm</sub>)**\n\n**3. Z<sup>[2]</sup><sub>10xm</sub> = W<sup>[2]</sup><sub>10x10</sub> A<sup>[1]</sup><sub>10xm</sub> + b<sup>[2]</sup><sub>10x1 => 10xm</sub>**\n\n**4. A<sup>[2]</sup> = softmax(Z<sup>[2]</sup>)**\n","metadata":{}},{"cell_type":"code","source":"def init_params():\n    W1 = np.random.rand(10, 784) - 0.5\n    b1 = np.random.rand(10, 1) - 0.5\n    W2 = np.random.rand(10, 10) - 0.5\n    b2 = np.random.rand(10,1) - 0.5\n    return W1, b1, W2, b2\n    \ndef ReLU(Z):\n    return np.maximum(0, Z)\n    \n    \ndef softmax(Z):\n    Z -= np.max(Z, axis=0)  # Subtract max value for numerical stability\n    A = np.exp(Z) / np.sum(np.exp(Z), axis=0)\n    return A\n\n    \ndef forward_prop(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\n\ndef one_hot(Y):\n    one_hot_Y = np.zeros((Y.size, Y.max() + 1))\n    one_hot_Y[np.arange(Y.size), Y] = 1 # now each row represents an example\n    one_hot_Y = one_hot_Y.T #now each column is an example\n    return one_hot_Y\n\n\ndef deriv_ReLU(Z):\n    return Z > 0\n\n\ndef back_prop(Z1, A1, Z2, A2, W2, X, Y):\n    one_hot_Y = one_hot(Y)\n    \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) * deriv_ReLU(Z1)\n    dW1 = 1/m * dZ1.dot(X.T)\n    db1 = 1/m * np.sum(dZ1)\n    return dW1, db1, dW2, db2\n\n\ndef update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha):\n    W1 -= alpha * dW1\n    b1 -= alpha * db1\n    W2 -= alpha * dW2\n    b2 -= alpha * db2\n    return W1, b1, W2, b2","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:13.066508Z","iopub.execute_input":"2024-02-25T09:11:13.067333Z","iopub.status.idle":"2024-02-25T09:11:13.081922Z","shell.execute_reply.started":"2024-02-25T09:11:13.067305Z","shell.execute_reply":"2024-02-25T09:11:13.080629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_predictions(A2):\n    return np.argmax(A2, 0) \n    \"\"\"\n    returns index of max value along index 0, i.e, returning the columnwise maximum,\n    basically returning a row maxtrix where each column contains the index,\n    that the NN thinks it should be labelled as.\n    \"\"\"\n\n\ndef get_accuracy(predictions, Y):\n    print(predictions, Y)\n    return np.sum(predictions == Y)/Y.size\n\n\ndef gradient_descent(X, Y, iterations, alpha):\n    W1, b1, W2, b2 = init_params()\n    for i in range(iterations):\n        Z1, A1, Z2, A2 = forward_prop(W1, b1, W2, b2, X)\n        dW1, db1, dW2, db2 = back_prop(Z1, A1, Z2, A2, W2, X, Y)\n        W1, b1, W2, b2 = update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha)\n        if i%50 == 0:\n            print(f\"Iteration: {i}\")\n            predictions = get_predictions(A2)\n            print(f\"Accuracy: {get_accuracy(predictions, Y)}\")\n    return W1, b1, W2, b2","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:13.085387Z","iopub.execute_input":"2024-02-25T09:11:13.085752Z","iopub.status.idle":"2024-02-25T09:11:13.097073Z","shell.execute_reply.started":"2024-02-25T09:11:13.085725Z","shell.execute_reply":"2024-02-25T09:11:13.095961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"W1, b1, W2, b2 = gradient_descent(X_train, Y_train, 1000, 0.08)","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:11:13.097945Z","iopub.execute_input":"2024-02-25T09:11:13.098261Z","iopub.status.idle":"2024-02-25T09:13:23.899610Z","shell.execute_reply.started":"2024-02-25T09:11:13.098234Z","shell.execute_reply":"2024-02-25T09:13:23.898031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dev_predictions = get_predictions(forward_prop(W1, b1, W2, b2, X_dev)[-1])\ndev_accuracy = get_accuracy(dev_predictions, Y_dev)\nprint(f\"Dev set accuracy: {dev_accuracy}\")","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:13:23.907026Z","iopub.execute_input":"2024-02-25T09:13:23.908454Z","iopub.status.idle":"2024-02-25T09:13:23.937698Z","shell.execute_reply.started":"2024-02-25T09:13:23.908413Z","shell.execute_reply":"2024-02-25T09:13:23.936472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_predictions(X, W1, b1, W2, b2):\n    A2 = forward_prop(W1, b1, W2, b2, X)[-1]\n    predictions = get_predictions(A2)\n    return predictions\n\ndef test_prediction(index, W1, b1, W2, b2):\n    current_image = X_train[:, index, None]\n    print(X_train.shape)\n    print(m)\n    prediction = make_predictions(X_train[:, index, None], W1, b1, W2, b2)\n    label = Y_train[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()\n    \ndef test_prediction(W1, b1, W2, b2):\n    index = random.randint(0, X_train.shape[1] - 1)\n    current_image = X_train[:, index, None]\n    prediction = make_predictions(X_train[:, index, None], W1, b1, W2, b2)\n    label = Y_train[index]\n    print(\"Index: \", 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":{"execution":{"iopub.status.busy":"2024-02-25T09:20:14.571904Z","iopub.execute_input":"2024-02-25T09:20:14.572280Z","iopub.status.idle":"2024-02-25T09:20:14.584253Z","shell.execute_reply.started":"2024-02-25T09:20:14.572252Z","shell.execute_reply":"2024-02-25T09:20:14.583036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for _ in range(10):\n    test_prediction(W1, b1, W2, b2)","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:20:52.009739Z","iopub.execute_input":"2024-02-25T09:20:52.010152Z","iopub.status.idle":"2024-02-25T09:20:53.751413Z","shell.execute_reply.started":"2024-02-25T09:20:52.010121Z","shell.execute_reply":"2024-02-25T09:20:53.750579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:13:23.953835Z","iopub.execute_input":"2024-02-25T09:13:23.954596Z","iopub.status.idle":"2024-02-25T09:13:26.352414Z","shell.execute_reply.started":"2024-02-25T09:13:23.954560Z","shell.execute_reply":"2024-02-25T09:13:26.351399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = np.array(test_data)\nm_test, n_test = test_data.shape\ntest_data = test_data.T\nX_test = test_data\nX_test = X_test / 255.","metadata":{"execution":{"iopub.status.busy":"2024-02-25T09:13:26.354015Z","iopub.execute_input":"2024-02-25T09:13:26.354503Z","iopub.status.idle":"2024-02-25T09:13:26.547819Z","shell.execute_reply.started":"2024-02-25T09:13:26.354465Z","shell.execute_reply":"2024-02-25T09:13:26.546853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}