{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport cv2\nfrom matplotlib.pyplot import imshow\nimport matplotlib.cm as cm\nimport matplotlib.pylab as plt\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport PIL\nfrom PIL import ImageFilter\nimport cv2\nimport itertools\nimport random\nfrom tensorflow import keras\nimport os\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D , UpSampling2D ,Conv2DTranspose\nfrom tensorflow.keras import backend as K\nimport tensorflow as tf\n \n%matplotlib inline","metadata":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_x = train.iloc[:,1:].values\ntrain_y = train.label.values\n\ntest_x = test.values","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img = []\n\nfor i in range(train_x.shape[0]):\n  img = train_x[i].reshape(28,28)\n\n  img = np.array(img, dtype=np.uint8)\n\n  kernel = np.ones((3,3),np.uint8)\n  img = cv2.dilate(img, kernel, iterations = 1)\n  img = cv2.erode(img, kernel, iterations = 1)\n\n  img = cv2.resize(img, (32,32))\n    \n\n  img[np.where(img > 150)] = 255\n  img[np.where(img <= 150)] = 0\n    \n  img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n  \n  train_img.append(img)\n\ntrain_img = np.array(train_img)\n\nprint(train_img.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_img = []\n\nfor i in range(test_x.shape[0]):\n  img = test_x[i].reshape(28,28)\n\n  img = np.array(img, dtype=np.uint8)\n\n  kernel = np.ones((3,3),np.uint8)\n  img = cv2.dilate(img, kernel, iterations = 1)\n  img = cv2.erode(img, kernel, iterations = 1)\n\n  img = cv2.resize(img, (32,32))\n    \n  img[np.where(img > 150)] = 255\n  img[np.where(img <= 150)] = 0\n    \n  img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n  \n  test_img.append(img)\n\ntest_img = np.array(test_img)\n\nprint(test_img.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_train_x, img_val_x, img_train_y, img_val_y = train_test_split(train_img, train_y, test_size = 0.2, random_state = 42)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = tf.keras.applications.ResNet50V2(input_shape=(32,32, 3),\n                                            include_top=False)\nbase_model.trainable = True\n\npreprocess_input = tf.keras.applications.resnet_v2.preprocess_input\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\n\ndef create_model():\n\n    #inputs = tf.keras.Input(shape=IMG_SHAPE)\n    #x = preprocess_input(inputs)\n    x = base_model.output\n\n    x = global_average_layer(x)\n    x = tf.keras.layers.Flatten()(x)\n\n    x = tf.keras.layers.Dense(4096,activation=('relu'))(x)\n    x = tf.keras.layers.Dropout(0.5)(x)\n\n    outputs = Dense(10, activation=('softmax'))(x)\n        \n    model = tf.keras.Model(base_model.input, outputs)\n\n    return model","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#this is for colab or cpu train\nmodel = create_model()\n\nbase_learning_rate = 0.0001\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),\n              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n              metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(img_train_x, img_train_y,shuffle=True,\n          batch_size=512,\n          epochs=10,\n          verbose=1,\n          validation_data=(img_val_x, img_val_y))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit = [['ImageId', 'Label']]\n\nfor i in range(test_img.shape[0]):\n  if i % 100 == 0:\n    print(i)\n  img = test_img[i]\n  img = img[None, :,:,:]\n  y = model.predict(img)\n  y = np.argmax(y,axis=1)\n  \n  submit.append([i+1, y[0]])\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit_df = pd.DataFrame(submit)\nsubmit_df.columns = submit_df.iloc[0]\nsubmit_df = submit_df.drop(0, axis = 0)\n\nsubmit_df.to_csv('Final_Submission.csv', index = False)","metadata":{},"execution_count":null,"outputs":[]}]}