{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30746,"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","execution":{"iopub.status.busy":"2024-08-10T15:56:47.722980Z","iopub.execute_input":"2024-08-10T15:56:47.723397Z","iopub.status.idle":"2024-08-10T15:56:47.733486Z","shell.execute_reply.started":"2024-08-10T15:56:47.723366Z","shell.execute_reply":"2024-08-10T15:56:47.731990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\ndef show_mnist(images, labels, predicted_labels=None):\n    plt.figure(figsize=(10,10))\n    for i in range(16):\n        plt.subplot(4,4, i+1)\n        plt.xticks([])\n        plt.yticks([])\n        plt.grid(False)\n        plt.imshow(images[i], cmap=plt.cm.gray)\n        if predicted_labels is not None:\n            title_obj = plt.title(f\"Real: {labels[i]}. Pred: {predicted_labels[i]}\")\n            if labels[i] != predicted_labels[i]:\n                plt.setp(title_obj, color='r')\n        else:\n            plt.title(f\"Real label: {labels[i]}\")","metadata":{"execution":{"iopub.status.busy":"2024-08-10T15:56:48.456754Z","iopub.execute_input":"2024-08-10T15:56:48.457176Z","iopub.status.idle":"2024-08-10T15:56:53.846558Z","shell.execute_reply.started":"2024-08-10T15:56:48.457146Z","shell.execute_reply":"2024-08-10T15:56:53.845147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train.drop('label', axis=1)\nY = train['label']\nX = X.to_numpy()\nY = Y.to_numpy()\nreshaped_X = X.reshape((42000, 28, 28))\nshow_mnist(reshaped_X, Y, predicted_labels=None)","metadata":{"execution":{"iopub.status.busy":"2024-08-10T15:56:53.848701Z","iopub.execute_input":"2024-08-10T15:56:53.849210Z","iopub.status.idle":"2024-08-10T15:56:55.032100Z","shell.execute_reply.started":"2024-08-10T15:56:53.849170Z","shell.execute_reply":"2024-08-10T15:56:55.030618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#X, Y = X / 255.0, Y / 255.0\nx_train, x_test, y_train, y_test = train_test_split(\n    X, Y, random_state=1, test_size=0.2\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-10T15:57:02.042386Z","iopub.execute_input":"2024-08-10T15:57:02.042835Z","iopub.status.idle":"2024-08-10T15:57:02.477807Z","shell.execute_reply.started":"2024-08-10T15:57:02.042803Z","shell.execute_reply":"2024-08-10T15:57:02.476546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot","metadata":{"execution":{"iopub.status.busy":"2024-08-10T15:53:53.531373Z","iopub.execute_input":"2024-08-10T15:53:53.531756Z","iopub.status.idle":"2024-08-10T15:54:10.844947Z","shell.execute_reply.started":"2024-08-10T15:53:53.531724Z","shell.execute_reply":"2024-08-10T15:54:10.842841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom livelossplot.tf_keras import PlotLossesCallback\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\n\nx_train = x_train.reshape((-1, 28*28)) \nx_test = x_test.reshape((-1, 28*28))\n\nmodel = Sequential([\n    Flatten(input_shape=(784,)),\n    Dense(128, activation='relu'),\n    Dense(128, activation='relu'),    \n    Dense(10, activation='softmax')\n])\n\nloss = 'sparse_categorical_crossentropy'\nmodel.compile(optimizer='adam',\n              loss=loss,\n              metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, validation_data=(x_test, y_test),\n          epochs=30, steps_per_epoch=50, batch_size=128, verbose=1, callbacks=[PlotLossesCallback()])","metadata":{"execution":{"iopub.status.busy":"2024-08-10T16:08:12.143456Z","iopub.execute_input":"2024-08-10T16:08:12.143903Z","iopub.status.idle":"2024-08-10T16:08:46.936138Z","shell.execute_reply.started":"2024-08-10T16:08:12.143869Z","shell.execute_reply":"2024-08-10T16:08:46.934787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_labels = np.argmax(model.predict(x_test), axis=-1)\nidxs = np.random.choice(np.arange(len(x_test)), 16, replace=False)\nshow_mnist(x_test[idxs].reshape((-1, 28, 28)), y_test[idxs], predicted_labels[idxs])","metadata":{"execution":{"iopub.status.busy":"2024-08-10T16:10:58.802546Z","iopub.execute_input":"2024-08-10T16:10:58.802991Z","iopub.status.idle":"2024-08-10T16:11:01.074459Z","shell.execute_reply.started":"2024-08-10T16:10:58.802949Z","shell.execute_reply":"2024-08-10T16:11:01.073077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = test.to_numpy()\n\npredicted_labels = np.argmax(model.predict(test), axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-08-10T16:15:15.392086Z","iopub.execute_input":"2024-08-10T16:15:15.392580Z","iopub.status.idle":"2024-08-10T16:15:17.579432Z","shell.execute_reply.started":"2024-08-10T16:15:15.392546Z","shell.execute_reply":"2024-08-10T16:15:17.578019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"columns = ['ImageId1', 'Label']\n\nsubmission = pd.DataFrame({columns[0]: range(1, 28001), columns[1]: predicted_labels})\nsubmission","metadata":{"execution":{"iopub.status.busy":"2024-08-10T16:26:12.613717Z","iopub.execute_input":"2024-08-10T16:26:12.614268Z","iopub.status.idle":"2024-08-10T16:26:12.629560Z","shell.execute_reply.started":"2024-08-10T16:26:12.614229Z","shell.execute_reply":"2024-08-10T16:26:12.628229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}