{"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":30579,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom matplotlib import pyplot as plt\nimport random","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-15T06:50:24.173579Z","iopub.execute_input":"2023-11-15T06:50:24.174084Z","iopub.status.idle":"2023-11-15T06:50:24.181994Z","shell.execute_reply.started":"2023-11-15T06:50:24.174048Z","shell.execute_reply":"2023-11-15T06:50:24.179830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:24.184867Z","iopub.execute_input":"2023-11-15T06:50:24.185954Z","iopub.status.idle":"2023-11-15T06:50:29.770551Z","shell.execute_reply.started":"2023-11-15T06:50:24.185821Z","shell.execute_reply":"2023-11-15T06:50:29.769589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = np.array(train_data).T\ntest_data = np.array(test_data).T\nm, n = train_data.shape\n\ny_train = train_data[0]\nx_train = train_data[1:]\nx_train = x_train / 255.0\n\ny_test = train_data[0]\nx_test = test_data\nx_test = x_test/255.0\n_,m_train = x_train.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:29.771939Z","iopub.execute_input":"2023-11-15T06:50:29.772515Z","iopub.status.idle":"2023-11-15T06:50:30.205971Z","shell.execute_reply.started":"2023-11-15T06:50:29.772483Z","shell.execute_reply":"2023-11-15T06:50:30.205005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:30.208395Z","iopub.execute_input":"2023-11-15T06:50:30.209119Z","iopub.status.idle":"2023-11-15T06:50:30.214989Z","shell.execute_reply.started":"2023-11-15T06:50:30.209078Z","shell.execute_reply":"2023-11-15T06:50:30.214238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 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\n\ndef ReLU(Z):\n    return np.maximum(Z, 0)\n\ndef d_dx_ReLU(Z):\n    return Z > 0\n\ndef softmax(Z):\n    exp_Z = np.exp(Z - np.max(Z, axis=0, keepdims=True))\n    A = exp_Z / np.sum(exp_Z, axis=0, keepdims=True)\n    return A\n    \ndef forward_pass(X, W1, b1, W2, b2):\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\ndef one_hot_encode(Y):\n    one_hot_Y = np.zeros((Y.size, Y.max() + 1))\n    one_hot_Y[np.arange(Y.size), Y] = 1\n    one_hot_Y = one_hot_Y.T\n    return one_hot_Y\n    \ndef backward_pass(X, Y, Z1, A1, Z2, A2, W1, W2):\n    m = Y.size\n    one_hot_Y = one_hot_encode(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) * d_dx_ReLU(Z1)\n    dW1 = (1 / m) * dZ1.dot(X.T)\n    db1 = (1 / m) * np.sum(dZ1)\n    return dW1, db1, dW2, db2","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:30.217369Z","iopub.execute_input":"2023-11-15T06:50:30.217943Z","iopub.status.idle":"2023-11-15T06:50:30.265853Z","shell.execute_reply.started":"2023-11-15T06:50:30.217913Z","shell.execute_reply":"2023-11-15T06:50:30.264841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def evaluate(predictions, Y):\n    correct = np.sum(predictions == Y)\n    accuracy = (correct/Y.size) * 100\n    return accuracy\n\ndef get_predictions(A2):\n    return np.argmax(A2, 0)\n\ndef gradient_descent(X, Y, epochs, alpha):\n    W1, b1, W2, b2 =  init_params()\n    for epoch in range(epochs):\n        Z1, A1, Z2, A2 = forward_pass(X, W1, b1, W2, b2)\n        dW1, db1, dW2, db2 = backward_pass(X, Y, Z1, A1, Z2, A2, W1, W2)\n        W1, b1, W2, b2 = update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha)\n        if epoch % 10 == 0 or epoch == 499:\n            print(\"Epoch: \", epoch)\n            print(\"Accuracy: \", evaluate(get_predictions(A2), Y))\n    return W1, b1, W2, b2","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:30.267539Z","iopub.execute_input":"2023-11-15T06:50:30.267932Z","iopub.status.idle":"2023-11-15T06:50:30.284006Z","shell.execute_reply.started":"2023-11-15T06:50:30.267899Z","shell.execute_reply":"2023-11-15T06:50:30.282461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"W1, b1, W2, b2 = gradient_descent(x_train, y_train, 500, 0.1)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:50:30.286192Z","iopub.execute_input":"2023-11-15T06:50:30.287082Z","iopub.status.idle":"2023-11-15T06:52:02.040268Z","shell.execute_reply.started":"2023-11-15T06:50:30.286990Z","shell.execute_reply":"2023-11-15T06:52:02.038498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import csv \n\ndef make_predictions(X, W1, b1, W2, b2):\n    _, _, _, A2 = forward_pass(X, W1, b1, W2, b2)\n    predictions = get_predictions(A2)\n    return predictions\n\ndef test_prediction(index, W1, b1, W2, b2):\n    current_image = x_test[:, index, None]\n    prediction = make_predictions(x_test[:, index, None], W1, b1, W2, b2)[0]\n#     print(\"Image ID: \", index)\n#     print(\"Prediction: \", prediction)\n    with open('submission.csv', 'a', newline='') as csvfile:\n        # Create a CSV writer\n        csv_writer = csv.writer(csvfile)\n        \n        # If it's a new file, write the header\n        if csvfile.tell() == 0:\n            csv_writer.writerow(['ImageID', 'Label'])\n        \n        # Write the data\n        csv_writer.writerow([index+1, prediction])\n    \n#     to print the images when testing\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":"2023-11-15T06:56:15.554938Z","iopub.execute_input":"2023-11-15T06:56:15.556435Z","iopub.status.idle":"2023-11-15T06:56:15.568606Z","shell.execute_reply.started":"2023-11-15T06:56:15.556390Z","shell.execute_reply":"2023-11-15T06:56:15.566658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(x_test.shape[1]):\n    test_prediction(i, W1, b1, W2, b2)","metadata":{"execution":{"iopub.status.busy":"2023-11-15T06:56:18.430851Z","iopub.execute_input":"2023-11-15T06:56:18.431386Z","iopub.status.idle":"2023-11-15T06:56:21.912704Z","shell.execute_reply.started":"2023-11-15T06:56:18.431347Z","shell.execute_reply":"2023-11-15T06:56:21.911249Z"},"trusted":true},"execution_count":null,"outputs":[]}]}