{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# Import necessary modules\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\n\nimport itertools\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.optimizers import Adam\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.utils import to_categorical\nfrom tensorflow.python.keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.python.keras.utils.vis_utils import model_to_dot\nfrom tensorflow.python.keras.applications.vgg16 import VGG16\nfrom tensorflow.python.keras.applications.resnet50 import ResNet50,preprocess_input\nfrom sklearn.model_selection import train_test_split,KFold, cross_val_score, GridSearchCV\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator,load_img, img_to_array\nfrom tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D,BatchNormalization,Dropout,Conv2D,MaxPool2D\n\nsns.set(style = \"white\", context = \"notebook\", palette = \"deep\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Preprocessing datasets\n# 1.Load datasets\nos.listdir(\"../input/Kannada-MNIST\")\ntrain = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ntest = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\n\n# 2.Delete label \"label\" and \"id\" in order to reshaping\nY_train = train[\"label\"]\nX_train = train.drop(labels = [\"label\"],axis = 1)\nX_test = test.drop(labels = [\"id\"],axis = 1)\n\n# 3.Reshape each flatten image into 28x28 square image and make the train label into categorical matrix\nX_train = X_train.values.reshape(-1,28,28)\nX_test = X_test.values.reshape(-1,28,28)\nY_train = to_categorical(Y_train,num_classes = 10)\ndel train,test\n\n# 4.In order to use Resnet-50, we need transfer 28x28 image into 32x32 image, here we expand the each border of iamge\n#   with the np.r_ and np.c_ .\nnew_Cols = np.zeros([28,2])\nnew_Rows = np.zeros([2,32])\nexpand_X_train = np.zeros([len(X_train),32,32])\nexpand_X_test = np.zeros([len(X_test),32,32])\n\nfor i in range(len(X_train)):\n    X_temp = np.c_[new_Cols,X_train[i]]\n    X_temp = np.c_[X_temp,new_Cols]\n    X_temp = np.r_[new_Rows,X_temp]\n    expand_X_train[i] = np.r_[X_temp,new_Rows]\n    \nfor i in range(len(X_test)):\n    X_temp = np.c_[new_Cols,X_test[i]]\n    X_temp = np.c_[X_temp,new_Cols]\n    X_temp = np.r_[new_Rows,X_temp]\n    expand_X_test[i] = np.r_[X_temp,new_Rows]\n    \n# 5.In order to use Resnet-50, I added 3 channels into every image\nnew_X_train = np.zeros([len(X_train),32,32,3])\nnew_X_test = np.zeros([len(X_test),32,32,3])\n\nX_train = expand_X_train.reshape(-1,32,32,1)\nX_test = expand_X_test.reshape(-1,32,32,1)\n\nnew_X_train[:,:,:,] = X_train\nnew_X_test[:,:,:,] = X_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 6.Split the train and validation data from the orignal train datasets \nrandom_seed = 2019\nX_train,X_val,Y_train,Y_val = train_test_split(new_X_train,Y_train,test_size=0.15,random_state = random_seed)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Build the model with Resnet-50, an outer Dataset:resnet50 should be added before\nresnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\nmodel = Sequential()\nmodel.add(ResNet50(include_top=False,input_tensor=None,input_shape=(32,32,3),pooling='avg',classes=10,weights=resnet_weights_path))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(BatchNormalization())\nmodel.add(Dense(10, activation='softmax'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Compile the model and Set some parameters.\nmodel.compile(optimizer=Adam(lr=0.0001),loss='categorical_crossentropy',metrics=['accuracy'])\nred_lr= ReduceLROnPlateau(monitor='val_acc',patience=3,verbose=1,factor=0.7)\nbatch_size=256\nepochs=30","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# With data augmentation to prevent overfitting\n# datagen = ImageDataGenerator(\n#         featurewise_center=False,  # set input mean to 0 over the dataset\n#         samplewise_center=False,  # set each sample mean to 0\n#         featurewise_std_normalization=False,  # divide inputs by std of the dataset\n#         samplewise_std_normalization=False,  # divide each input by its std\n#         zca_whitening=False,  # apply ZCA whitening\n#         rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n#         zoom_range = 0.1, # Randomly zoom image \n#         width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n#         height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n#         horizontal_flip=False,  # randomly flip images\n#         vertical_flip=False)  # randomly flip images\n\n# datagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# Fit the model\n# history = model.fit_generator(datagen.flow(X_train,Y_train, batch_size = batch_size),\n#                               epochs = epochs, validation_data = (X_val,Y_val),\n#                               verbose = 1, steps_per_epoch = X_train.shape[0] // batch_size\n#                               , callbacks=[red_lr])  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit the model\nhistory = model.fit(X_train,Y_train, batch_size = batch_size,epochs = epochs, validation_data = (X_val,Y_val),verbose = 1, callbacks=[red_lr])  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Predict the label of the test datasets\nY_pred = model.predict(new_X_test)\nY_pred = np.argmax(Y_pred,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Make a submission\nsample_sub = pd.read_csv(\"../input/Kannada-MNIST/sample_submission.csv\")\nsample_sub['label'] = Y_pred\nsample_sub.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}