{"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":30761,"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\n# Load and prepare data\ndf = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\").values\nnp.random.shuffle(df)\ndf_dev = df[:1000].T\nY_dev = df_dev[0]\nX_dev = df_dev[1:] / 255\ndf_train = df[1000:].T\nY_train = df_train[0]\nX_train = df_train[1:] / 255\n\n# Load and prepare test data\ndf_test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\").values\nX_test = df_test.T / 255\n\nm, n = X_train.shape\n\ndef init_params():\n    W1 = np.random.randn(10, 784) * 0.01\n    b1 = np.zeros((10, 1))\n    W2 = np.random.randn(10, 10) * 0.01\n    b2 = np.zeros((10, 1))\n    return W1, b1, W2, b2\n\ndef ReLU(Z):\n    return np.maximum(Z, 0)\n\ndef softmax(Z):\n    exp_Z = np.exp(Z - np.max(Z, axis=0, keepdims=True))  # Numerical stability\n    return exp_Z / np.sum(exp_Z, axis=0, keepdims=True)\n\ndef forward_prop(W1, b1, W2, b2, X):\n    Z1 = np.dot(W1, X) + b1\n    A1 = ReLU(Z1)\n    Z2 = np.dot(W2, A1) + b2\n    A2 = softmax(Z2)\n    return Z1, A1, Z2, A2\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    return one_hot_Y.T\n\ndef cross_entropy_loss(A2, Y):\n    one_hot_Y = one_hot(Y)\n    m = Y.shape[0]\n    loss = -np.sum(one_hot_Y * np.log(A2 + 1e-8)) / m  # Adding a small epsilon for numerical stability\n    return loss\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 * np.dot(dZ2, A1.T)\n    db2 = 1 / m * np.sum(dZ2, axis=1, keepdims=True)\n    dZ1 = np.dot(W2.T, dZ2) * ReLU_deriv(Z1)\n    dW1 = 1 / m * np.dot(dZ1, X.T)\n    db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True)\n    return dW1, db1, dW2, db2\n\ndef update_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha):\n    W1 -= alpha * dW1\n    b1 -= alpha * db1    \n    W2 -= alpha * dW2  \n    b2 -= alpha * db2    \n    return W1, b1, W2, b2\n\ndef prediction(A2):\n    return np.argmax(A2, axis=0)\n\ndef accuracy(predictions, Y):\n    return np.mean(predictions == Y)\n\ndef gradient_descent(X, Y, alpha, iterations):\n    W1, b1, W2, b2 = init_params()\n    for i in range(iterations):\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_params(W1, b1, W2, b2, dW1, db1, dW2, db2, alpha)\n        if i % 10 == 0:\n            predictions = prediction(A2)\n            train_acc = accuracy(predictions, Y)\n            loss = cross_entropy_loss(A2, Y)\n            print(f\"Iteration {i}: Training accuracy = {train_acc * 100:.2f}%, Loss = {loss:.4f}\")\n    return W1, b1, W2, b2\n\ndef make_predictions(X, W1, b1, W2, b2):\n    _, _, _, A2 = forward_prop(W1, b1, W2, b2, X)\n    predictions = prediction(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\ndef evaluate_model(X, W1, b1, W2, b2):\n    _, _, _, A2 = forward_prop(W1, b1, W2, b2, X)\n    predictions = prediction(A2)\n    return predictions\n\ndef visualize_test_prediction(index, X_test, predictions):\n    current_image = X_test[:, index].reshape((28, 28)) * 255\n    plt.gray()\n    plt.imshow(current_image, interpolation='nearest')\n    plt.title(f\"Predicted: {predictions[index]}\")\n    plt.show()\n\n# Train the model\nprint(\"Training the model...\")\nW1, b1, W2, b2 = gradient_descent(X_train, Y_train, alpha=0.01, iterations=500)\n\n# Make predictions on test data\nprint(\"\\nMaking predictions on test data...\")\ntest_predictions = evaluate_model(X_test, W1, b1, W2, b2)\n\n# Print some test predictions\nprint(\"\\nSample test predictions:\")\nfor i in range(10):  # Print first 10 predictions\n    print(f\"Image {i+1}: Predicted digit {test_predictions[i]}\")\n\n# Visualize a few test predictions\nprint(\"\\nVisualizing some test predictions:\")\nfor i in range(5):  # Change to any number of images you want to visualize\n    visualize_test_prediction(i, X_test, test_predictions)\n\n\nsubmission = pd.DataFrame({'ImageId': range(1, len(test_predictions) + 1),\n                          'Label': test_predictions})\nsubmission.to_csv('submission.csv', index=False)\nprint(\"\\nSubmission file created: 'submission.csv'\")\n\n# Optional: Test on some training examples\nprint(\"\\nTesting on some training examples:\")\nfor i in range(5):  # Change to any number of images you want to test\n    test_prediction(i, W1, b1, W2, b2)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-24T10:42:13.100541Z","iopub.execute_input":"2024-08-24T10:42:13.101073Z","iopub.status.idle":"2024-08-24T10:43:12.576670Z","shell.execute_reply.started":"2024-08-24T10:42:13.101027Z","shell.execute_reply":"2024-08-24T10:43:12.575436Z"},"trusted":true},"execution_count":null,"outputs":[]}]}