{"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":"# 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 pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage import data, io, filters\n\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":"2022-12-16T12:35:16.904654Z","iopub.execute_input":"2022-12-16T12:35:16.905275Z","iopub.status.idle":"2022-12-16T12:35:18.336492Z","shell.execute_reply.started":"2022-12-16T12:35:16.905189Z","shell.execute_reply":"2022-12-16T12:35:18.335195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images = train.iloc[:, 1:].values.reshape(-1, 28, 28)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(train_images[50], cmap='gray')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from skimage.transform import resize\ntrain_images = np.array([resize(image, (18, 18)) for image in train_images])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(train_images[50], cmap='gray', interpolation='nearest')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(train_images, train.iloc[:, 0], test_size=0.2, random_state=0)\n\nprint(X_train.shape)\nprint(X_val.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sc = StandardScaler()\nX_train = sc.fit_transform(X_train.reshape(-1, 18*18)).reshape(-1, 18, 18)\nX_val = sc.transform(X_val.reshape(-1, 18*18)).reshape(-1, 18, 18)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.Sequential([\n    layers.Flatten(input_shape=(18, 18)),\n    layers.Dense(256, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(X_train, y_train, epochs=25, validation_data=(X_val, y_val))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(2,1)\nax[0].plot(model.history.history['accuracy'], color='b', label=\"Training accuracy\")\nax[0].plot(model.history.history['val_accuracy'], color='r', label=\"validation accuracy\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(model.history.history['loss'], color='b', label=\"Training loss\")\nax[1].plot(model.history.history['val_loss'], color='r',label=\"Validation loss\")\nlegend = ax[1].legend(loc='best', shadow=True)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_images = test.values.reshape(-1, 28, 28)\ntest_images = np.array([resize(image, (18, 18)) for image in test_images])\ntest_images = sc.transform(test_images.reshape(-1, 18*18)).reshape(-1, 18, 18)\npredictions = model.predict(test_images)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = np.argmax(predictions,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"/kaggle/working/submission.csv\",index=False)","metadata":{},"execution_count":null,"outputs":[]}]}