{"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":30822,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ndata = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:08:00.960799Z","iopub.execute_input":"2025-01-01T19:08:00.961258Z","iopub.status.idle":"2025-01-01T19:08:03.314712Z","shell.execute_reply.started":"2025-01-01T19:08:00.961215Z","shell.execute_reply":"2025-01-01T19:08:03.313549Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:08:03.316958Z","iopub.execute_input":"2025-01-01T19:08:03.317364Z","iopub.status.idle":"2025-01-01T19:08:03.334448Z","shell.execute_reply.started":"2025-01-01T19:08:03.317315Z","shell.execute_reply":"2025-01-01T19:08:03.332898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = np.array(data)       # Converts the data into a NumPy array, allowing for efficient numerical operations\nm, n = data.shape           # Gets the dimensions of the data (m = number of rows, n = number of columns)\nnp.random.shuffle(data)     # Shuffles the data randomly to avoid any bias or overfitting during training\n\ndata_dev = data[0:1000].T   # Selects the first 1000 rows from the data and transposes it (changes rows to columns)\nY_dev = data[0]             # Selects the first row of data as the target variable (Y) for development set\nX_dev = data[1: n]          # Selects the remaining rows as the features (X) for the development set\nX_dev = X_dev / 255.0   \n\ndata_train = data[1000: m].T  # Selects the remaining data (from row 1000 to m) and transposes it for the training set\nY_train = data_train[0]     # Selects the first row of the transposed training data as the target variable (Y)\nX_train = data_train[1: n]  # Selects the remaining rows of the transposed training data as the features (X)\nX_train = X_train / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:18:05.712495Z","iopub.execute_input":"2025-01-01T19:18:05.712980Z","iopub.status.idle":"2025-01-01T19:18:06.516267Z","shell.execute_reply.started":"2025-01-01T19:18:05.712946Z","shell.execute_reply":"2025-01-01T19:18:06.515093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train[:, 0].shape ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:08:04.189527Z","iopub.execute_input":"2025-01-01T19:08:04.189884Z","iopub.status.idle":"2025-01-01T19:08:04.197229Z","shell.execute_reply.started":"2025-01-01T19:08:04.189855Z","shell.execute_reply":"2025-01-01T19:08:04.195603Z"}},"outputs":[],"execution_count":null},{"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(Z, 0)\n\ndef softmax(Z):\n    expZ = np.exp(Z - np.max(Z, axis=0, keepdims=True))  # Subtract max for numerical stability\n    return expZ / np.sum(expZ, axis=0, keepdims=True)\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\ndef ReLU_deriv(Z):\n    return Z > 0\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\n    one_hot_Y = one_hot_Y.T\n    return one_hot_Y\n\ndef backward_prop(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, axis=1, keepdims=True)\n    dZ1 = W2.T.dot(dZ2) * ReLU_deriv(Z1)\n    dW1 = 1 / m * dZ1.dot(X.T)\n    db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True)\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-01-01T19:08:04.198729Z","iopub.execute_input":"2025-01-01T19:08:04.199104Z","iopub.status.idle":"2025-01-01T19:08:04.217669Z","shell.execute_reply.started":"2025-01-01T19:08:04.199074Z","shell.execute_reply":"2025-01-01T19:08:04.216552Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_predictions(A2):\n    return np.argmax(A2, 0)\n\ndef get_accuracy(predictions, Y):\n    print(predictions, Y)\n    return np.sum(predictions == Y) / Y.size\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_prop(W1, b1, W2, b2, X)\n        dW1, db1, dW2, db2 = backward_prop(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 % 10 == 0:\n            print(\"Iteration: \", i)\n            predictions = get_predictions(A2)\n            print(get_accuracy(predictions, Y))\n    return W1, b1, W2, b2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:08:04.218890Z","iopub.execute_input":"2025-01-01T19:08:04.219281Z","iopub.status.idle":"2025-01-01T19:08:04.242427Z","shell.execute_reply.started":"2025-01-01T19:08:04.219239Z","shell.execute_reply":"2025-01-01T19:08:04.241306Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example Usage (assuming X_train and Y_train are preloaded and normalized):\n# X_train: (784, number of samples), Y_train: (number of samples,)\nW1, b1, W2, b2 = gradient_descent(X_train, Y_train, 0.10, 500)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:09:56.221406Z","iopub.execute_input":"2025-01-01T19:09:56.221792Z","iopub.status.idle":"2025-01-01T19:10:54.411326Z","shell.execute_reply.started":"2025-01-01T19:09:56.221737Z","shell.execute_reply":"2025-01-01T19:10:54.409948Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def make_predictions(X, W1, b1, W2, b2):\n    _, _, _, A2 = forward_prop(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 = X_train[:, index, None]\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()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:10:58.107277Z","iopub.execute_input":"2025-01-01T19:10:58.107614Z","iopub.status.idle":"2025-01-01T19:10:58.114288Z","shell.execute_reply.started":"2025-01-01T19:10:58.107587Z","shell.execute_reply":"2025-01-01T19:10:58.112905Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_prediction(0, W1, b1, W2, b2)\ntest_prediction(1, W1, b1, W2, b2)\ntest_prediction(2, W1, b1, W2, b2)\ntest_prediction(3, W1, b1, W2, b2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-01T19:11:00.148614Z","iopub.execute_input":"2025-01-01T19:11:00.149158Z","iopub.status.idle":"2025-01-01T19:11:01.069463Z","shell.execute_reply.started":"2025-01-01T19:11:00.149111Z","shell.execute_reply":"2025-01-01T19:11:01.068361Z"}},"outputs":[],"execution_count":null}]}