{"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 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":"2022-06-03T19:09:03.171162Z","iopub.execute_input":"2022-06-03T19:09:03.171552Z","iopub.status.idle":"2022-06-03T19:09:03.201525Z","shell.execute_reply.started":"2022-06-03T19:09:03.171474Z","shell.execute_reply":"2022-06-03T19:09:03.200625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Load Data**","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:03.203391Z","iopub.execute_input":"2022-06-03T19:09:03.203795Z","iopub.status.idle":"2022-06-03T19:09:06.318116Z","shell.execute_reply.started":"2022-06-03T19:09:03.203757Z","shell.execute_reply":"2022-06-03T19:09:06.317331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:06.319759Z","iopub.execute_input":"2022-06-03T19:09:06.320201Z","iopub.status.idle":"2022-06-03T19:09:08.173148Z","shell.execute_reply.started":"2022-06-03T19:09:06.320164Z","shell.execute_reply":"2022-06-03T19:09:08.172406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nsample_submission.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:08.174566Z","iopub.execute_input":"2022-06-03T19:09:08.175161Z","iopub.status.idle":"2022-06-03T19:09:09.771171Z","shell.execute_reply.started":"2022-06-03T19:09:08.175124Z","shell.execute_reply":"2022-06-03T19:09:09.770437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:09.773005Z","iopub.execute_input":"2022-06-03T19:09:09.773507Z","iopub.status.idle":"2022-06-03T19:09:09.779016Z","shell.execute_reply.started":"2022-06-03T19:09:09.773472Z","shell.execute_reply":"2022-06-03T19:09:09.778250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:09.780325Z","iopub.execute_input":"2022-06-03T19:09:09.780904Z","iopub.status.idle":"2022-06-03T19:09:09.790518Z","shell.execute_reply.started":"2022-06-03T19:09:09.780868Z","shell.execute_reply":"2022-06-03T19:09:09.789486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.describe()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:09.792096Z","iopub.execute_input":"2022-06-03T19:09:09.792565Z","iopub.status.idle":"2022-06-03T19:09:11.826270Z","shell.execute_reply.started":"2022-06-03T19:09:09.792526Z","shell.execute_reply":"2022-06-03T19:09:11.825491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport missingno\nimport seaborn as sns\nplt.style.use('seaborn-whitegrid')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:11.827753Z","iopub.execute_input":"2022-06-03T19:09:11.828090Z","iopub.status.idle":"2022-06-03T19:09:12.263221Z","shell.execute_reply.started":"2022-06-03T19:09:11.828057Z","shell.execute_reply":"2022-06-03T19:09:12.262336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Start Python Imports\nimport math, time, random, datetime","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:12.264971Z","iopub.execute_input":"2022-06-03T19:09:12.268588Z","iopub.status.idle":"2022-06-03T19:09:12.272153Z","shell.execute_reply.started":"2022-06-03T19:09:12.268547Z","shell.execute_reply":"2022-06-03T19:09:12.271377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def generateData(filepath):\n    file = pd.read_csv(filepath)\n    \n    imageDataset = []\n    # only the train dataset has labels, take labels and turn it into a list\n    if 'train' in filepath:\n        labelDataset = file.loc[:,'label'].values.tolist()\n    else:\n        labelDataset = []\n    \n    #go through each line of the file\n    for i in range(len(file)):        \n        #the test csv does not contain a label column so we have to start from the first column\n        start = 1\n        if 'test' in filepath:\n            start = 0\n        currentLine = file.loc[i]\n        image = np.array(currentLine[start:len(file.loc[i])])\n        #reshape the 1D aray into a 2D matrix and normalize the data\n        image = image.reshape(28,28)\n        image = image / 255\n        imageDataset.append(image)\n     \n    #turn the lists into numpy arrays and expand their dimensions because keras is picky\n    imageDataset = np.array(imageDataset)\n    labelDataset = np.array(labelDataset)\n    imageDataset = np.expand_dims(imageDataset, -1)\n    labelDataset = np.expand_dims(labelDataset, -1)\n    print('Images shape and amount: ', type(imageDataset), imageDataset.shape)\n    print('Labels shape and amount: ', type(labelDataset), labelDataset.shape)\n    return imageDataset, labelDataset\ntrainImages, trainLabels = generateData(r'/kaggle/input/digit-recognizer/train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:12.273671Z","iopub.execute_input":"2022-06-03T19:09:12.274214Z","iopub.status.idle":"2022-06-03T19:09:23.201065Z","shell.execute_reply.started":"2022-06-03T19:09:12.274180Z","shell.execute_reply":"2022-06-03T19:09:23.200077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainImages.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:23.204246Z","iopub.execute_input":"2022-06-03T19:09:23.204713Z","iopub.status.idle":"2022-06-03T19:09:23.210238Z","shell.execute_reply.started":"2022-06-03T19:09:23.204676Z","shell.execute_reply":"2022-06-03T19:09:23.209207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainLabels.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:23.211695Z","iopub.execute_input":"2022-06-03T19:09:23.212091Z","iopub.status.idle":"2022-06-03T19:09:23.222653Z","shell.execute_reply.started":"2022-06-03T19:09:23.212054Z","shell.execute_reply":"2022-06-03T19:09:23.221084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainLabels","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:23.224108Z","iopub.execute_input":"2022-06-03T19:09:23.224525Z","iopub.status.idle":"2022-06-03T19:09:23.232125Z","shell.execute_reply.started":"2022-06-03T19:09:23.224490Z","shell.execute_reply":"2022-06-03T19:09:23.231301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(10, 10))\n#rd.seed(None)\nfor i in range(16):\n    fig.add_subplot(4, 4, i+1)\n    rdNumber = random.randint(0,42000)\n    plt.title(trainLabels[rdNumber][0])\n    plt.imshow(trainImages[rdNumber], cmap='Greys_r')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:23.233735Z","iopub.execute_input":"2022-06-03T19:09:23.234462Z","iopub.status.idle":"2022-06-03T19:09:24.481831Z","shell.execute_reply.started":"2022-06-03T19:09:23.234344Z","shell.execute_reply":"2022-06-03T19:09:24.481086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\n\ny_train = to_categorical(trainLabels)\ny_train","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:24.483136Z","iopub.execute_input":"2022-06-03T19:09:24.483657Z","iopub.status.idle":"2022-06-03T19:09:29.971314Z","shell.execute_reply.started":"2022-06-03T19:09:24.483620Z","shell.execute_reply":"2022-06-03T19:09:29.970474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = trainImages","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:29.972687Z","iopub.execute_input":"2022-06-03T19:09:29.973394Z","iopub.status.idle":"2022-06-03T19:09:29.979354Z","shell.execute_reply.started":"2022-06-03T19:09:29.973357Z","shell.execute_reply":"2022-06-03T19:09:29.976644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Dense, Dropout\nimport pandas as pd\nfrom keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:29.983604Z","iopub.execute_input":"2022-06-03T19:09:29.983909Z","iopub.status.idle":"2022-06-03T19:09:29.997010Z","shell.execute_reply.started":"2022-06-03T19:09:29.983884Z","shell.execute_reply":"2022-06-03T19:09:29.996238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# CREATE MORE IMAGES VIA DATA AUGMENTATION\ndatagen = ImageDataGenerator(\n        rotation_range=10,  \n        zoom_range = 0.10,  \n        width_shift_range=0.1, \n        height_shift_range=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:29.998277Z","iopub.execute_input":"2022-06-03T19:09:29.998838Z","iopub.status.idle":"2022-06-03T19:09:30.009228Z","shell.execute_reply.started":"2022-06-03T19:09:29.998797Z","shell.execute_reply":"2022-06-03T19:09:30.008275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32,kernel_size=3,activation='relu',input_shape=(28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32,kernel_size=5,strides=2,padding='same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(64,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64,kernel_size=3,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64,kernel_size=5,strides=2,padding='same',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\nmodel.add(Dense(10, activation='softmax'))\n\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:30.012505Z","iopub.execute_input":"2022-06-03T19:09:30.012817Z","iopub.status.idle":"2022-06-03T19:09:33.070797Z","shell.execute_reply.started":"2022-06-03T19:09:30.012793Z","shell.execute_reply":"2022-06-03T19:09:33.070006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:33.072057Z","iopub.execute_input":"2022-06-03T19:09:33.072557Z","iopub.status.idle":"2022-06-03T19:09:33.084788Z","shell.execute_reply.started":"2022-06-03T19:09:33.072522Z","shell.execute_reply":"2022-06-03T19:09:33.083969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(datagen.flow(x_train,y_train, batch_size=64), epochs = 100, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:09:33.086277Z","iopub.execute_input":"2022-06-03T19:09:33.086669Z","iopub.status.idle":"2022-06-03T19:31:30.711463Z","shell.execute_reply.started":"2022-06-03T19:09:33.086632Z","shell.execute_reply":"2022-06-03T19:31:30.710629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# DECREASE LEARNING RATE EACH EPOCH\n# annealer = LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x)\n# history = model.fit_generator(datagen.flow(x_train,y_train, batch_size=64), epochs = 25, steps_per_epoch = x_train.shape[0]//64, callbacks=[annealer], verbose=0)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:30.714993Z","iopub.execute_input":"2022-06-03T19:31:30.715338Z","iopub.status.idle":"2022-06-03T19:31:30.720250Z","shell.execute_reply.started":"2022-06-03T19:31:30.715308Z","shell.execute_reply":"2022-06-03T19:31:30.718160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get predictions and Save","metadata":{}},{"cell_type":"code","source":"testImages, testLabels = generateData(r'/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:30.721878Z","iopub.execute_input":"2022-06-03T19:31:30.722731Z","iopub.status.idle":"2022-06-03T19:31:38.237730Z","shell.execute_reply.started":"2022-06-03T19:31:30.722695Z","shell.execute_reply":"2022-06-03T19:31:38.236061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test = testImages\ny_test = testLabels","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:38.239209Z","iopub.execute_input":"2022-06-03T19:31:38.240119Z","iopub.status.idle":"2022-06-03T19:31:38.244144Z","shell.execute_reply.started":"2022-06-03T19:31:38.240079Z","shell.execute_reply":"2022-06-03T19:31:38.243366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(x_test, verbose=2)\npredictions","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:38.245294Z","iopub.execute_input":"2022-06-03T19:31:38.246234Z","iopub.status.idle":"2022-06-03T19:31:41.159250Z","shell.execute_reply.started":"2022-06-03T19:31:38.246175Z","shell.execute_reply":"2022-06-03T19:31:41.158472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictionsLabel = np.argmax(predictions, axis=1)\nprint(type(predictionsLabel), len(predictionsLabel), predictionsLabel.shape, predictionsLabel)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:41.160444Z","iopub.execute_input":"2022-06-03T19:31:41.160816Z","iopub.status.idle":"2022-06-03T19:31:41.167223Z","shell.execute_reply.started":"2022-06-03T19:31:41.160790Z","shell.execute_reply":"2022-06-03T19:31:41.166388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.DataFrame({'ImageId': [i for i in range(1,len(predictionsLabel)+1)], 'Label': predictionsLabel})\ndf","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:41.168510Z","iopub.execute_input":"2022-06-03T19:31:41.169341Z","iopub.status.idle":"2022-06-03T19:31:41.195458Z","shell.execute_reply.started":"2022-06-03T19:31:41.169300Z","shell.execute_reply":"2022-06-03T19:31:41.194611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:41.196492Z","iopub.execute_input":"2022-06-03T19:31:41.196855Z","iopub.status.idle":"2022-06-03T19:31:41.219222Z","shell.execute_reply.started":"2022-06-03T19:31:41.196820Z","shell.execute_reply":"2022-06-03T19:31:41.218477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv('/kaggle/working/predictions.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:41.222838Z","iopub.execute_input":"2022-06-03T19:31:41.223104Z","iopub.status.idle":"2022-06-03T19:31:41.279505Z","shell.execute_reply.started":"2022-06-03T19:31:41.223081Z","shell.execute_reply":"2022-06-03T19:31:41.278589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('/kaggle/working')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:41.283874Z","iopub.execute_input":"2022-06-03T19:31:41.286105Z","iopub.status.idle":"2022-06-03T19:31:44.835241Z","shell.execute_reply.started":"2022-06-03T19:31:41.286068Z","shell.execute_reply":"2022-06-03T19:31:44.834466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions.shape\n","metadata":{"execution":{"iopub.status.busy":"2022-06-03T19:31:44.842040Z","iopub.execute_input":"2022-06-03T19:31:44.842366Z","iopub.status.idle":"2022-06-03T19:31:44.849870Z","shell.execute_reply.started":"2022-06-03T19:31:44.842340Z","shell.execute_reply":"2022-06-03T19:31:44.847415Z"},"trusted":true},"execution_count":null,"outputs":[]}]}