{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 2 Hidden Layers MNIST NN\n","metadata":{}},{"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","execution":{"iopub.status.busy":"2022-02-23T06:37:27.743136Z","iopub.execute_input":"2022-02-23T06:37:27.744375Z","iopub.status.idle":"2022-02-23T06:37:30.636459Z","shell.execute_reply.started":"2022-02-23T06:37:27.744295Z","shell.execute_reply":"2022-02-23T06:37:30.635458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = np.array(data)\nm, n = data.shape\nnp.random.shuffle(data) # shuffle before splitting into dev and training sets\n\ndata_dev = data[0:1000].T\nY_dev = data_dev[0]\nX_dev = data_dev[1:n]\nX_dev = X_dev / 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","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:30.638825Z","iopub.execute_input":"2022-02-23T06:37:30.639304Z","iopub.status.idle":"2022-02-23T06:37:31.429688Z","shell.execute_reply.started":"2022-02-23T06:37:30.639256Z","shell.execute_reply":"2022-02-23T06:37:31.428884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_train","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:31.431026Z","iopub.execute_input":"2022-02-23T06:37:31.431544Z","iopub.status.idle":"2022-02-23T06:37:31.437468Z","shell.execute_reply.started":"2022-02-23T06:37:31.431511Z","shell.execute_reply":"2022-02-23T06:37:31.436485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Forward propagation**\n\n$$Z^{[1]} = W^{[1]} X + b^{[1]}$$\n$$A^{[1]} = g_{\\text{ReLU}}(Z^{[1]}))$$\n$$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$$\n$$A^{[2]} = g_{\\text{ReLU}}(Z^{[2]})$$\n$$Z^{[3]} = W^{[3]} A^{[2]} + b^{[3]}$$\n$$A^{[3]} = g_{\\text{softmax}}(Z^{[3]})$$\n\n**Backward propagation**\n$$dZ^{[3]} = A^{[3]} - Y$$\n$$dW^{[3]} = \\frac{1}{m} dZ^{[3]} A^{[2]T}$$\n$$dB^{[3]} = \\frac{1}{m} \\Sigma {dZ^{[3]}}$$\n$$dZ^{[2]} = A^{[2]} - Y$$\n$$dW^{[2]} = \\frac{1}{m} dZ^{[2]} A^{[1]T}$$\n$$dB^{[2]} = \\frac{1}{m} \\Sigma {dZ^{[2]}}$$\n$$dZ^{[1]} = W^{[2]T} dZ^{[2]} .* g^{[1]\\prime} (z^{[1]})$$\n$$dW^{[1]} = \\frac{1}{m} dZ^{[1]} A^{[0]T}$$\n$$dB^{[1]} = \\frac{1}{m} \\Sigma {dZ^{[1]}}$$\n\n**Parameter updates**\n\n$$W^{[3]} := W^{[3]} - \\alpha dW^{[3]}$$\n$$b^{[3]} := b^{[3]} - \\alpha db^{[3]}$$\n$$W^{[2]} := W^{[2]} - \\alpha dW^{[2]}$$\n$$b^{[2]} := b^{[2]} - \\alpha db^{[2]}$$\n$$W^{[1]} := W^{[1]} - \\alpha dW^{[1]}$$\n$$b^{[1]} := b^{[1]} - \\alpha db^{[1]}$$\n\n**Vars and shapes**\n\nForward prop\n\n- $A^{[0]} = X$: 784 x m\n- $Z^{[1]} \\sim A^{[1]}$: 70 x m\n- $W^{[1]}$: 70 x 784 (as $W^{[1]} A^{[0]} \\sim Z^{[1]}$)\n- $B^{[1]}$: 70 x 1\n- $Z^{[2]} \\sim A^{[2]}$: 50 x m\n- $W^{[2]}$: 50 x 70 (as $W^{[2]} A^{[1]} \\sim Z^{[2]}$)\n- $B^{[2]}$: 50 x 1\n- $Z^{[3]} \\sim A^{[3]}$: 10 x m\n- $W^{[3]}$: 10 x 50 (as $W^{[3]} A^{[2]} \\sim Z^{[3]}$)\n- $B^{[3]}$: 10 x 1\n\nBackprop\n\n- $dZ^{[3]}$: 10 x m ($~A^{[3]}$)\n- $dW^{[3]}$: 10 x 50\n- $dB^{[3]}$: 10 x 1\n- $dZ^{[2]}$: 50 x m ($~A^{[2]}$)\n- $dW^{[2]}$: 50 x 70\n- $dB^{[2]}$: 50 x 1\n- $dZ^{[1]}$: 70 x m ($~A^{[1]}$)\n- $dW^{[1]}$: 70 x 70\n- $dB^{[1]}$: 70 x 1","metadata":{}},{"cell_type":"code","source":"def init_params():\n    W1 = np.random.rand(70, 784) - 0.5\n    b1 = np.random.rand(70, 1) - 0.5\n    W2 = np.random.rand(50, 70) - 0.5\n    b2 = np.random.rand(50, 1) - 0.5\n    W3 = np.random.rand(10, 50) - 0.5\n    b3 = np.random.rand(10, 1) - 0.5\n    return W1, b1, W2, b2, W3, b3\n\ndef ReLU(Z):\n    return np.maximum(Z, 0)\n\ndef softmax(Z):\n    A = np.exp(Z) / sum(np.exp(Z))\n    return A\n    \ndef forward_prop(W1, b1, W2, b2, W3, b3, X):\n    Z1 = W1.dot(X) + b1\n    A1 = ReLU(Z1)\n    Z2 = W2.dot(A1) + b2\n    A2 = ReLU(Z2)\n    Z3 = W3.dot(A2) + b3\n    A3 = softmax(Z3)\n    return Z1, A1, Z2, A2, Z3, A3\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, Z3, A3, W1, W2, W3, X, Y):\n    one_hot_Y = one_hot(Y)\n    dZ3 = A3 - one_hot_Y\n    dW3 = 1 / m * dZ3.dot(A2.T)\n    db3 = 1 / m * np.sum(dZ3)\n    dZ2 = W3.T.dot(dZ3) * ReLU_deriv(Z2)\n    dW2 = 1 / m * dZ2.dot(A1.T)\n    db2 = 1 / m * np.sum(dZ2)\n    dZ1 = W2.T.dot(dZ2) * ReLU_deriv(Z1)\n    dW1 = 1 / m * dZ1.dot(X.T)\n    db1 = 1 / m * np.sum(dZ1)\n    return dW1, db1, dW2, db2, dW3, db3\n\ndef update_params(W1, b1, W2, b2, W3, b3, dW1, db1, dW2, db2, dW3, db3, alpha):\n    W1 = W1 - alpha * dW1\n    b1 = b1 - alpha * db1    \n    W2 = W2 - alpha * dW2  \n    b2 = b2 - alpha * db2    \n    W3 = W3 - alpha * dW3  \n    b3 = b3 - alpha * db3\n    return W1, b1, W2, b2, W3, b3","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:31.439254Z","iopub.execute_input":"2022-02-23T06:37:31.439547Z","iopub.status.idle":"2022-02-23T06:37:31.463354Z","shell.execute_reply.started":"2022-02-23T06:37:31.439519Z","shell.execute_reply":"2022-02-23T06:37:31.462533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"init_params()","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:31.465738Z","iopub.execute_input":"2022-02-23T06:37:31.466075Z","iopub.status.idle":"2022-02-23T06:37:31.4913Z","shell.execute_reply.started":"2022-02-23T06:37:31.466045Z","shell.execute_reply":"2022-02-23T06:37:31.490427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_predictions(A3):\n    return np.argmax(A3, 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, W3, b3 = init_params()\n    for i in range (iterations):\n        Z1, A1, Z2, A2, Z3, A3 = forward_prop(W1, b1, W2, b2, W3, b3, X)\n        dW1, db1, dW2, db2, dW3, db3 = backward_prop(Z1, A1, Z2, A2, Z3, A3, W1, W2, W3, X, Y)\n        W1, b1, W2, b2, W3, b3 = update_params(W1, b1, W2, b2, W3, b3, dW1, db1, dW2, db2, dW3, db3, alpha)\n        predictions = get_predictions(A3)\n        if i % 10 == 0:\n            print(\"Iteration: \", i)\n            predictions = get_predictions(A3)\n            print(get_accuracy(predictions, Y))\n    return W1, b1, W2, b2, W3, b3","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:31.493051Z","iopub.execute_input":"2022-02-23T06:37:31.493353Z","iopub.status.idle":"2022-02-23T06:37:31.505784Z","shell.execute_reply.started":"2022-02-23T06:37:31.493323Z","shell.execute_reply":"2022-02-23T06:37:31.504853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"W1, b1, W2, b2, W3, b3 = gradient_descent(X_train, Y_train, 0.35, 500)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:37:31.507071Z","iopub.execute_input":"2022-02-23T06:37:31.507546Z","iopub.status.idle":"2022-02-23T06:39:50.129917Z","shell.execute_reply.started":"2022-02-23T06:37:31.507514Z","shell.execute_reply":"2022-02-23T06:39:50.128775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"~93% accuracy on training set.","metadata":{}},{"cell_type":"code","source":"def make_predictions(X, W1, b1, W2, b2, W3, b3 ):\n    _, _, _, _, _, A3 = forward_prop(W1, b1, W2, b2, W3, b3, X)\n    predictions = get_predictions(A3)\n    return predictions\n\ndef test_prediction(index, W1, b1, W2, b2, W3, b3):\n    current_image = X_train[:, index, None]\n    prediction = make_predictions(X_train[:, index, None], W1, b1, W2, b2, W3, b3)\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":{"execution":{"iopub.status.busy":"2022-02-23T06:39:50.131479Z","iopub.execute_input":"2022-02-23T06:39:50.131881Z","iopub.status.idle":"2022-02-23T06:39:50.143097Z","shell.execute_reply.started":"2022-02-23T06:39:50.13184Z","shell.execute_reply":"2022-02-23T06:39:50.141925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's look at a couple of examples:","metadata":{}},{"cell_type":"code","source":"test_prediction(0, W1, b1, W2, b2, W3, b3)\ntest_prediction(1, W1, b1, W2, b2, W3, b3)\ntest_prediction(2, W1, b1, W2, b2, W3, b3)\ntest_prediction(3, W1, b1, W2, b2, W3, b3)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:39:50.144842Z","iopub.execute_input":"2022-02-23T06:39:50.145442Z","iopub.status.idle":"2022-02-23T06:39:50.703753Z","shell.execute_reply.started":"2022-02-23T06:39:50.145399Z","shell.execute_reply":"2022-02-23T06:39:50.703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Finally, let's find the accuracy on the dev set:","metadata":{}},{"cell_type":"code","source":"dev_predictions = make_predictions(X_dev, W1, b1, W2, b2, W3, b3)\nget_accuracy(dev_predictions, Y_dev)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:39:50.704631Z","iopub.execute_input":"2022-02-23T06:39:50.704891Z","iopub.status.idle":"2022-02-23T06:39:50.721998Z","shell.execute_reply.started":"2022-02-23T06:39:50.704864Z","shell.execute_reply":"2022-02-23T06:39:50.721266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Still 91% accuracy, so our model generalized from the training data pretty well.","metadata":{}}]}