{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31012,"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:08.239344Z","iopub.execute_input":"2025-04-28T08:03:08.239665Z","iopub.status.idle":"2025-04-28T08:03:13.890264Z","shell.execute_reply.started":"2025-04-28T08:03:08.239577Z","shell.execute_reply":"2025-04-28T08:03:13.889340Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:13.891115Z","iopub.execute_input":"2025-04-28T08:03:13.891335Z","iopub.status.idle":"2025-04-28T08:03:13.919126Z","shell.execute_reply.started":"2025-04-28T08:03:13.891317Z","shell.execute_reply":"2025-04-28T08:03:13.918268Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = np.array(data)\nm, n = data.shape\nnp.random.shuffle(data)\n\ndata_dev = data[0:1000].T\nX_dev = data_dev[1:n]\nY_dev = data_dev[0]\nx_dev = X_dev / 255.0\n\ndata_train = data[1000:m].T\nY_train = data_train[0]\nX_train = data_train[1:n]\nX_train = X_train / 255.0\n_,m_train = X_train.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:13.921265Z","iopub.execute_input":"2025-04-28T08:03:13.921580Z","iopub.status.idle":"2025-04-28T08:03:14.725888Z","shell.execute_reply.started":"2025-04-28T08:03:13.921552Z","shell.execute_reply":"2025-04-28T08:03:14.725173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(Y_train.shape)\nprint(X_train.shape)\nY_train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:14.726662Z","iopub.execute_input":"2025-04-28T08:03:14.726969Z","iopub.status.idle":"2025-04-28T08:03:14.734151Z","shell.execute_reply.started":"2025-04-28T08:03:14.726947Z","shell.execute_reply":"2025-04-28T08:03:14.733448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def init_params():\n    W1 = np.random.rand(10, 784) * np.sqrt(2. / 784) \n    b1 = np.zeros((10, 1))  \n    W2 = np.random.rand(10, 10) * np.sqrt(2. / 10) \n    b2 = np.zeros((10, 1))  \n    return W1, W2, b1, b2\n\ndef ReLU(Z):\n    return np.maximum(0, Z)\n\ndef softmax(Z):\n    Z_shifted = Z - np.max(Z, axis=0, keepdims=True)\n    exp_Z = np.exp(Z_shifted)\n    softmax_Z = exp_Z / np.sum(exp_Z, axis=0, keepdims=True)\n    return softmax_Z\n\ndef forward_prop(W1, W2, b1, 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, Z2, A1, A2\n    \ndef deriv_ReLU(Z):\n    return (Z > 0).astype(float)\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 back_prop(Z1, Z2, W1, W2, A1, A2, X, Y):\n    one_hot_Y = one_hot(Y)\n    m = Y.size\n    print(\"A2 shape:\", A2.shape)\n    print(\"one_hot_Y shape:\", one_hot_Y.shape)\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) * deriv_ReLU(Z1)\n    dW1 = 1 / m * dZ1.dot(X.T)\n    db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True)\n    return dW1, dW2, db1, db2\n\ndef update_params(W1, W2, b1, b2, dW1, dW2, db1, 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, W2, b1, b2 \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:14.735491Z","iopub.execute_input":"2025-04-28T08:03:14.735786Z","iopub.status.idle":"2025-04-28T08:03:14.750290Z","shell.execute_reply.started":"2025-04-28T08:03:14.735764Z","shell.execute_reply":"2025-04-28T08:03:14.749473Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_predictions(A2):\n    return np.argmax(A2, 0)\n\ndef get_accuracy(prediction, Y):\n    print(prediction, Y)\n    return np.sum(prediction == Y) / Y.size\n\ndef compute_loss(A2, Y):\n    m =  Y.size\n    one_hot_Y = one_hot(Y)\n    A2_clipped = np.clip(A2, 1e-8, 1 - 1e-8)\n    loss = -np.sum(one_hot_Y * np.log(A2 + 1e-8))\n    return loss\n\ndef gradient_descent(X, Y, alpha, iterations):\n    W1, W2, b1, b2 = init_params()\n    losses = []\n    for i in range(iterations):\n        Z1, Z2, A1, A2 = forward_prop(W1, W2, b1, b2, X)\n        dW1, dW2, db1, db2 = back_prop(Z1, Z2, W1, W2, A1, A2, X, Y)\n        W1, W2, b1, b2 = update_params(W1, W2, b1, b2, dW1, dW2, db1, db2, alpha)\n        if i % 10 == 0:\n          \n            predictions = get_predictions(A2)\n            print(\"Accuracy: \", get_accuracy(predictions, Y))\n            loss = compute_loss(A2, Y)\n            losses.append(loss)\n            print(f\"Iteration {i}: Loss = {loss}\")\n    return  W1, W2, b1, b2, losses\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:14.751127Z","iopub.execute_input":"2025-04-28T08:03:14.751772Z","iopub.status.idle":"2025-04-28T08:03:14.766355Z","shell.execute_reply.started":"2025-04-28T08:03:14.751751Z","shell.execute_reply":"2025-04-28T08:03:14.765655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"W1, W2, b1, b2, losses = gradient_descent(X_train, Y_train, alpha = 0.001, iterations = 40000)\n\nplt.plot(np.arange(0, 40000, 10), losses)\nplt.xlabel(\"iterations\")\nplt.ylabel(\"Loss\")\nplt.title(\"Loss vs iterations \")\nplt.grid(True)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-28T08:03:14.767219Z","iopub.execute_input":"2025-04-28T08:03:14.767539Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def make_predictions(X, W1, W2, b1, b2):\n    _,_,_, A2 = forward_prop(W1, W2, b1, b2, X)\n    predictions = get_predictions(A2)\n    return predictions\n\ndef test_prediction(index, W1, W2, b1, b2):\n    current_image = X_train[:, index, None]\n    prediction = make_predictions(X_train[:, index, None], W1, W2, b1, 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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_prediction(0, W1, W2, b1, b2)\ntest_prediction(1, W1, W2, b1, b2)\ntest_prediction(2, W1, W2, b1, b2)\ntest_prediction(3, W1, W2, b1, b2)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dev_prediction = make_predictions(X_dev, W1, W2, b1, b2)\nget_accuracy(dev_prediction, Y_dev)","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}