{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:21.581506Z","iopub.execute_input":"2024-11-28T18:43:21.581999Z","iopub.status.idle":"2024-11-28T18:43:21.592324Z","shell.execute_reply.started":"2024-11-28T18:43:21.581957Z","shell.execute_reply":"2024-11-28T18:43:21.591119Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:21.594526Z","iopub.execute_input":"2024-11-28T18:43:21.594963Z","iopub.status.idle":"2024-11-28T18:43:21.612692Z","shell.execute_reply.started":"2024-11-28T18:43:21.594923Z","shell.execute_reply":"2024-11-28T18:43:21.611229Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:21.614325Z","iopub.execute_input":"2024-11-28T18:43:21.614698Z","iopub.status.idle":"2024-11-28T18:43:24.121822Z","shell.execute_reply.started":"2024-11-28T18:43:21.614662Z","shell.execute_reply":"2024-11-28T18:43:24.120583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:24.124201Z","iopub.execute_input":"2024-11-28T18:43:24.124567Z","iopub.status.idle":"2024-11-28T18:43:28.123343Z","shell.execute_reply.started":"2024-11-28T18:43:24.124532Z","shell.execute_reply":"2024-11-28T18:43:28.122491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = np.array(train_data)\nrows, cols = data.shape\nnp.random.shuffle(data) # shuffle before splitting into dev and training sets\n\n_test_data = data[0:1000].T\ny_test = _test_data[0]\nX_test = _test_data[1:cols] / 255.\n\n_train_data = data[1000:rows].T\ny_train = _train_data[0]\nX_train = _train_data[1:cols] / 255.\n\nprint(f\"Y_train: {y_train}\")\nprint(f\"X_train shape: {X_train.shape}\")\nprint(f\"y_train shape: {y_train.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:28.125086Z","iopub.execute_input":"2024-11-28T18:43:28.125368Z","iopub.status.idle":"2024-11-28T18:43:28.901578Z","shell.execute_reply.started":"2024-11-28T18:43:28.125341Z","shell.execute_reply":"2024-11-28T18:43:28.900497Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Neural Network (with 2 Layers)","metadata":{}},{"cell_type":"code","source":"def init_params():\n    W1 = np.random.rand(10, 784) - 0.5 # weights1\n    b1 = np.random.rand(10, 1) - 0.5 # bias1\n    W2 = np.random.rand(10, 10) - 0.5 # weights2\n    b2 = np.random.rand(10, 1) - 0.5 # bias2\n    return W1, b1, W2, b2\n\ndef ReLU(Z): # returns 0 if the num is negative, else return the num\n    return np.maximum(Z, 0)\n\ndef softmax(Z):\n    return np.exp(Z) / sum(np.exp(Z))\n\ndef forward_prop(W1, b1, W2, b2, X):\n    Z1 = W1.dot(X) + b1 # Z1 correspond to the first layer, X would be the input layer and b the bias\n    A1 = ReLU(Z1) # A1 correspond to the first activation, in this case ReLU\n    Z2 = W2.dot(A1) + b2\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)) # create a matrix with zeros with the size of y\n    one_hot_y[np.arange(y.size), y] = 1 # change the value position from 0 to 1 (Ex.: 3 -> [0, 0, 0, 1, 0, 0, 0, 0, 0, 0])\n    one_hot_y = one_hot_y.T # T cause now each row is a example, and we want to be each columns\n    return one_hot_y\n\ndef ReLU_deriv(Z):\n    return Z > 0\n\ndef backward_prop(Z1, A1, Z2, A2, W1, W2, X, y):\n    rows = y.size\n    one_hot_y = one_hot(y)\n    # taking how much the second layer pred was off the true pred\n    dZ2 = A2 - one_hot_y\n    # calculate how much weights and bias contributed to the error\n    dW2 = 1 / rows * dZ2.dot(A1.T)\n    db2 = 1 / rows * np.sum(dZ2)\n    # getting the Layer 1 deriv, from the results of the Layer 2\n    dZ1 = W2.T.dot(dZ2) * ReLU_deriv(Z1)\n    # calculate how much weights and bias contributed to the error\n    dW1 = 1 / rows * dZ1.dot(X.T)\n    db1 = 1 / rows * np.sum(dZ1)\n    return dW1, db1, dW2, db2\n\ndef update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, learning_rate):\n    # update the last params with the news applying the learning_rate\n    W1 = W1 - learning_rate * dW1\n    b1 = b1 - learning_rate * db1\n    W2 = W2 - learning_rate * dW2\n    b2 = b2 - learning_rate * db2\n    return W1, b1, W2, b2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:28.903092Z","iopub.execute_input":"2024-11-28T18:43:28.903510Z","iopub.status.idle":"2024-11-28T18:43:28.915603Z","shell.execute_reply.started":"2024-11-28T18:43:28.903464Z","shell.execute_reply":"2024-11-28T18:43:28.914438Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_pred(A2):\n    return np.argmax(A2, 0)\n    \ndef get_accu(preds, true_values):\n    return np.sum(preds == true_values) / true_values.size # sum the amount of true preds and / for the total","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Algorithm","metadata":{}},{"cell_type":"code","source":"\ndef gradient_descent(X, y, iterations, learning_rate):\n    W1, b1, W2, b2 = init_params()\n    last_accu = 0\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, learning_rate)\n        if i % 100 == 0: # print every 100 iters\n            accu = get_accu(get_pred(A2), y)\n            print('Iteration: ', i)\n            print(get_pred(A2), y)\n            print('Accuracy: ', accu)\n            if accu < last_accu: # stopper when accu goes down\n                print('Stopping...')\n                break\n            last_accu = get_accu(get_pred(A2), y)\n    return W1, b1, W2, b2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:43:28.917078Z","iopub.execute_input":"2024-11-28T18:43:28.917510Z","iopub.status.idle":"2024-11-28T18:43:28.935504Z","shell.execute_reply.started":"2024-11-28T18:43:28.917451Z","shell.execute_reply":"2024-11-28T18:43:28.934512Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Trainning","metadata":{}},{"cell_type":"code","source":"iterations = 500\nlearning_rate = 0.1\n\nW1, b1, W2, b2 = gradient_descent(X_train, y_train, 500, learning_rate)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:46:00.787048Z","iopub.execute_input":"2024-11-28T18:46:00.787507Z","iopub.status.idle":"2024-11-28T18:46:59.165829Z","shell.execute_reply.started":"2024-11-28T18:46:00.787470Z","shell.execute_reply":"2024-11-28T18:46:59.164514Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predictions","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_pred(A2)\n    return predictions\n\ndef test_prediction(index, W1, b1, W2, b2, X, y):\n    current_image = X[:, index, None]\n    prediction = make_predictions(X[:, index, None], W1, b1, W2, b2)\n    label = y[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":"2024-11-28T18:47:08.786545Z","iopub.execute_input":"2024-11-28T18:47:08.786977Z","iopub.status.idle":"2024-11-28T18:47:08.795014Z","shell.execute_reply.started":"2024-11-28T18:47:08.786941Z","shell.execute_reply":"2024-11-28T18:47:08.793600Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_predictions = 4\n\nfor i in range(0, num_predictions):\n    test_prediction(np.random.randint(0, 59000), W1, b1, W2, b2, X_train, y_train)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:47:16.292326Z","iopub.execute_input":"2024-11-28T18:47:16.292774Z","iopub.status.idle":"2024-11-28T18:47:17.235754Z","shell.execute_reply.started":"2024-11-28T18:47:16.292709Z","shell.execute_reply":"2024-11-28T18:47:17.234567Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predictions on Test Data","metadata":{}},{"cell_type":"code","source":"test_predictions = make_predictions(X_test, W1, b1, W2, b2)\nget_accu(test_predictions, y_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-28T18:48:34.066054Z","iopub.execute_input":"2024-11-28T18:48:34.066461Z","iopub.status.idle":"2024-11-28T18:48:34.082572Z","shell.execute_reply.started":"2024-11-28T18:48:34.066426Z","shell.execute_reply":"2024-11-28T18:48:34.079074Z"}},"outputs":[],"execution_count":null}]}