{"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":"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\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\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-04-07T14:32:04.895862Z","iopub.execute_input":"2022-04-07T14:32:04.8968Z","iopub.status.idle":"2022-04-07T14:32:07.121529Z","shell.execute_reply.started":"2022-04-07T14:32:04.896729Z","shell.execute_reply":"2022-04-07T14:32:07.12075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Set up the notebook with the data loaded.","metadata":{}},{"cell_type":"code","source":"# we want to transpose this data frame, and perform linear algebra on it as a matrix so we make it a numpy array: \ndata = np.array(data) # we split this data between developement data and training data\n# essentially cross validating as we train to avoid overfitting\n# m rows consist of images, and n columns given pixel values for that images\nm, n = data.shape # m images, n features\nnp.random.shuffle(data) # mixes it up\n\ndata_dev = data[0:1000].T # first 1000 examples, and transposed\nY_dev = data_dev[0] # labels\nX_dev = data_dev[1:n] # features\nX_dev = X_dev / 255. # not 100% sure what this division does, or why \".\"\n\ndata_train = data[1000:m].T\nY_train = data_train[0] # labels\nX_train = data_train[1:n] # features\nX_train = X_train / 255.\n_, m_train = X_train.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-04-07T14:32:07.122895Z","iopub.execute_input":"2022-04-07T14:32:07.12311Z","iopub.status.idle":"2022-04-07T14:32:07.83842Z","shell.execute_reply.started":"2022-04-07T14:32:07.123084Z","shell.execute_reply":"2022-04-07T14:32:07.837563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now we have the numpy arrays ready to use.\n\nWe next define all the functions we'll be using to perform backwards propagation etc.\n\n*A special thanks to Smason Zhang (https://www.kaggle.com/wwsalmon) for the tutorial on implementing this network*.","metadata":{}},{"cell_type":"code","source":"# CREATING NEURAL NETWORK\n\n# Initialising paramters\n\ndef init_params():\n    # weights to first layer\n    W1 = np.random.rand(10, 784) - 0.5 # matrix with entries from distribution between 0 and 1 subtract 0.5, so now between -0.5 and 0.5\n    # biases to first layer\n    b1 = np.random.rand(10, 1) - 0.5\n    # weights to second layer\n    W2 = np.random.rand(10, 10) - 0.5 \n    # biases to first layer\n    b2 = np.random.rand(10, 1) - 0.5\n    \n    return W1, b1, W2, b2\n\n\ndef ReLU(Z):\n    return np.maximum(Z,0) # this essentially returns Z if if Z>0\n\ndef deriv_ReLU(Z):\n    return Z > 0 # slope of constant 0 or slope of linear (=1)\n    # booleans are converted to 0 or 1 so this works!\n\ndef softmax(Z):\n    A = np.exp(Z) / sum(np.exp(Z)) # exponential of each element in column is divided by the sum of the exponential of each row \n    return A # for whatever reason np.sum broke this. Yet sum works - these are meant to be pretty much interchangable!\n    # so columns is preserved but rows collapsed essentially\n\ndef forward_prop(W1, b1, W2, b2, X):\n    Z1 = W1.dot(X) + b1 # First layer = Weights*Input + Bias\n    A1 = ReLU(Z1)\n    Z2 = W2.dot(A1) + b2 # similar, note dot here as we have 2D arrays acts as matrix multiplication\n    A2 = softmax(Z2)\n    return Z1, A1, Z2, A2 \n\ndef one_hot(Y):\n    one_hot_Y = np.zeros((Y.size, Y.max() + 1)) # creates a matrix of zeros, of dimension m, 10 (classes are 0 through 9 so max is 9, then + 1 is 10)\n    one_hot_Y[np.arange(Y.size), Y] = 1 # first bit is an array 0 to m, lets us look at one row at a time, then for each row, go to the column\n    # specified by the label of Y, and set it to 1. e.g. if Y=4, for our given row we go to the fourth column and set it to = 1 so we get our ( 0 0 0 1 0 0 0 0 0 0) vector\n    one_hot_Y = one_hot_Y.T # transposed so that each column is an example not each row\n    return one_hot_Y\n\ndef back_prop(Z1, A1, A2, W2, X, Y):\n    one_hot_Y = one_hot(Y) # correct output values\n    # second layer\n    dZ2 = A2 - one_hot_Y # so the difference between our prediction and the correct answer\n    dW2 = (1 / m) * dZ2.dot(A1.T) # derivative of loss function with respect to the weights. Gives us an average of the absolute error in the second layer\n    db2 = (1 / m) * np.sum(dZ2) # how much bias contributed to error\n    # first layer\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\n    return dW1, db1, dW2, db2 # return how much we need to update our weights and biases (parameters) by\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 get_predictions(A2):\n    return np.argmax(A2, 0) # so the output node with highest value is our prediction\n    # second argument is axis we look at \n\ndef get_accuracy(predictions, Y):\n    print(predictions, Y)\n    accuracy = np.sum(predictions == Y) / Y.size # proportion of correct predictions\n    return accuracy\n\n\ndef gradient_descent(X, Y, iterations, alpha): # the training \n    W1, b1, W2, b2 = init_params() # get random weights and biases\n    # run a loop of forwar prop -> back prop -> update params -> forward prop etc.\n    for i in range(iterations): # how many times we want to train\n        Z1, A1, _, A2 = forward_prop(W1, b1, W2, b2, X) # forward prop to calculate the layers\n        dW1, db1, dW2, db2 = back_prop(Z1, A1, A2, W2, X, Y) # backwards prop to find contributions to error\n        W1, b1, W2, b2 = update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha) # update the parameters based on those error contributions\n        if i % 10 == 0:\n            print(\"Iteration: \", i) # every 10 iterations we see how well we're doing\n            predictions = get_predictions(A2) # predictions from forward prop, and \n            print(\"Accuracy: \", get_accuracy(predictions, Y)) # see how accurate w.r.t Y (real outputs)\n    \n    return W1, b1, W2, b2 ","metadata":{"execution":{"iopub.status.busy":"2022-04-07T14:32:07.8406Z","iopub.execute_input":"2022-04-07T14:32:07.840926Z","iopub.status.idle":"2022-04-07T14:32:07.857134Z","shell.execute_reply.started":"2022-04-07T14:32:07.840886Z","shell.execute_reply":"2022-04-07T14:32:07.856401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's see it training LIVE:","metadata":{}},{"cell_type":"code","source":"# Perform training\nW1, b1, W2, b2 = gradient_descent(X_train, Y_train, 500, 0.1) # 500 iterations, learning rate of 0.01","metadata":{"execution":{"iopub.status.busy":"2022-04-07T14:32:07.858143Z","iopub.execute_input":"2022-04-07T14:32:07.858353Z","iopub.status.idle":"2022-04-07T14:33:16.16654Z","shell.execute_reply.started":"2022-04-07T14:32:07.858328Z","shell.execute_reply":"2022-04-07T14:33:16.165593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Some live classifications:**","metadata":{}},{"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()\n\n\ntest_prediction(0, W1, b1, W2, b2)\ntest_prediction(325, W1, b1, W2, b2)\ntest_prediction(23, W1, b1, W2, b2)\ntest_prediction(78, W1, b1, W2, b2)","metadata":{"execution":{"iopub.status.busy":"2022-04-07T14:33:16.168564Z","iopub.execute_input":"2022-04-07T14:33:16.169067Z","iopub.status.idle":"2022-04-07T14:33:16.820205Z","shell.execute_reply.started":"2022-04-07T14:33:16.169027Z","shell.execute_reply":"2022-04-07T14:33:16.819632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Finally we can have a look how the algorithm does on the validation set!","metadata":{}},{"cell_type":"code","source":"dev_predictions = make_predictions(X_dev, W1, b1, W2, b2)\nget_accuracy(dev_predictions, Y_dev)","metadata":{"execution":{"iopub.status.busy":"2022-04-07T14:33:16.821207Z","iopub.execute_input":"2022-04-07T14:33:16.821406Z","iopub.status.idle":"2022-04-07T14:33:16.848945Z","shell.execute_reply.started":"2022-04-07T14:33:16.821381Z","shell.execute_reply":"2022-04-07T14:33:16.848114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Not bad!","metadata":{}}]}