{"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":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Importing packages","metadata":{}},{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:27:46.700761Z","iopub.execute_input":"2025-03-31T10:27:46.701234Z","iopub.status.idle":"2025-03-31T10:27:46.706147Z","shell.execute_reply.started":"2025-03-31T10:27:46.701173Z","shell.execute_reply":"2025-03-31T10:27:46.705156Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Importing File","metadata":{}},{"cell_type":"code","source":"data=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:27:46.707354Z","iopub.execute_input":"2025-03-31T10:27:46.707682Z","iopub.status.idle":"2025-03-31T10:27:48.921286Z","shell.execute_reply.started":"2025-03-31T10:27:46.707649Z","shell.execute_reply":"2025-03-31T10:27:48.920193Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Arranging Data","metadata":{}},{"cell_type":"code","source":"data=np.array(data)\nm,n=data.shape\nnp.random.shuffle(data)\n\ndata_dev=data[0:1000].T\ny_dev=data_dev[0]\nx_dev=data_dev[1:n]\nx_dev=x_dev/255 #normalise pixel values assuming they are between 0 and 255\n\ndata_train=data[1000:m].T\ny_train=data_train[0]\nx_train=data_train[1:n]\nx_train=x_train/255\n_,m_train = x_train.shape #get number of training samples","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:27:48.923360Z","iopub.execute_input":"2025-03-31T10:27:48.923730Z","iopub.status.idle":"2025-03-31T10:27:49.727007Z","shell.execute_reply.started":"2025-03-31T10:27:48.923696Z","shell.execute_reply":"2025-03-31T10:27:49.726114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:27:49.728418Z","iopub.execute_input":"2025-03-31T10:27:49.728717Z","iopub.status.idle":"2025-03-31T10:27:49.734162Z","shell.execute_reply.started":"2025-03-31T10:27:49.728693Z","shell.execute_reply":"2025-03-31T10:27:49.733186Z"}},"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(0,z)\n\ndef softmax(z):\n    exp_z = np.exp(z - np.max(z, axis=0, keepdims=True))  # Prevent overflow\n    return exp_z / np.sum(exp_z, 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 one_hot(Y):\n    Y = np.asarray(Y, dtype=int).flatten()  # Ensure Y is a 1D integer array\n    num_classes = np.max(Y) + 1  # Get the number of unique classes\n    one_hot_Y = np.zeros((num_classes, Y.size), dtype=int)  # Create one-hot matrix\n    one_hot_Y[Y, np.arange(Y.size)] = 1  # Assign one-hot encoding\n    return one_hot_Y  # Shape: (num_classes, num_samples)\n\ndef deriv_relu(z):\n    return z>0\n    \ndef back_prop(z1,a1,z2,a2,w1,w2,X,Y):\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)*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\ndef update_param(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-03-31T10:27:49.735358Z","iopub.execute_input":"2025-03-31T10:27:49.735690Z","iopub.status.idle":"2025-03-31T10:27:49.754257Z","shell.execute_reply.started":"2025-03-31T10:27:49.735656Z","shell.execute_reply":"2025-03-31T10:27:49.753250Z"}},"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_dec(X,Y,iteration,alpha):\n    w1,b1,w2,b2=init_params()\n    for i in range (iteration):\n        z1,a1,z2,a2=forward_prop(w1,b1,w2,b2,X)\n        dw1,db1,dw2,db2=back_prop(z1,a1,z2,a2,w1,w2,X,Y)\n        w1,b1,w2,b2=update_param(w1,b1,w2,b2,dw1,db1,dw2,db2,alpha)\n        if i %50==0:\n            print('Iteration : ',i)\n            print('Accuracy : ',get_accuracy(get_predictions(a2),Y))\n    return w1,b1,w2,b2 \n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:29:08.546138Z","iopub.execute_input":"2025-03-31T10:29:08.546528Z","iopub.status.idle":"2025-03-31T10:29:08.553351Z","shell.execute_reply.started":"2025-03-31T10:29:08.546499Z","shell.execute_reply":"2025-03-31T10:29:08.552117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"w1,b1,w2,b2=gradient_dec(x_train,y_train,1000,0.1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:29:10.561094Z","iopub.execute_input":"2025-03-31T10:29:10.561448Z","iopub.status.idle":"2025-03-31T10:30:20.282132Z","shell.execute_reply.started":"2025-03-31T10:29:10.561420Z","shell.execute_reply":"2025-03-31T10:30:20.281308Z"}},"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-03-31T10:34:18.142255Z","iopub.execute_input":"2025-03-31T10:34:18.142606Z","iopub.status.idle":"2025-03-31T10:34:18.148623Z","shell.execute_reply.started":"2025-03-31T10:34:18.142577Z","shell.execute_reply":"2025-03-31T10:34:18.147421Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dev_predictions = make_predictions(x_dev, w1, b1, w2, b2)\nget_accuracy(dev_predictions, y_dev)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-31T10:34:51.767665Z","iopub.execute_input":"2025-03-31T10:34:51.767969Z","iopub.status.idle":"2025-03-31T10:34:51.780190Z","shell.execute_reply.started":"2025-03-31T10:34:51.767946Z","shell.execute_reply":"2025-03-31T10:34:51.779246Z"}},"outputs":[],"execution_count":null}]}