{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":true},"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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport shutil\nimport os\n\nimport matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_path = \"/kaggle/input/d-tribe-hackathon-2020/\"\ntrain = base_path + \"train/train\"\ntest = base_path + \"test\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission = pd.read_csv(base_path + \"sample submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndf_train_map = pd.read_csv(base_path + \"train/train map.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_map.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = list(df_train_map.LABEL)\nlen(labels), df_train_map[\"LABEL\"].nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_map[\"LABEL\"].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Creating multiple folders based on multiiple targets\n\ntraining_dataset = \"training_dataset\"\n\nfor label in labels:\n    os.makedirs(os.path.join(training_dataset, str(label)), exist_ok = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Copy train images to multiple lables folders\n\nfor i,j in df_train_map.iterrows():\n    shutil.copy(os.path.join(train,j.IMAGE), os.path.join(training_dataset, str(j.LABEL), j.IMAGE))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nfor i in range(6):\n    plt.subplot(1,6,i+1)\n    plt.imshow(training_dataset[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes =  df_train_map[\"LABEL\"].nunique()\nrows = 128\ncols = 128\nno_channel = 3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\n\nfrom keras.preprocessing.image import load_img, img_to_array","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model = Sequential()\n# #Input L\n# model.add(Conv2D(32, (3, 3), input_shape=(row, col, no_channel)))\n# model.add(Activation('relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n\n\n# #HL1\n# model.add(Conv2D(32, (3, 3)))\n# model.add(Activation('relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n\n# #HL2\n# model.add(Conv2D(64, (3, 3)))\n# model.add(Activation('relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n\n# # the model so far outputs 3D feature maps (height, width, features)\n# model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors\n# model.add(Dense(64))\n# model.add(Activation('relu'))\n\n# #output L\n# model.add(Dropout(0.5))\n# model.add(Dense(num_classes))\n# model.add(Activation('softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, kernel_size = (3,3), padding = \"same\", activation = \"relu\" , input_shape = (rows, cols, no_channel)))\n# model.add(BatchNormalization())\n\n#HL1\nmodel.add(Conv2D(64, kernel_size=(3,3), padding='same', activation='relu'))\n# model.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n#HL2\nmodel.add(Conv2D(128, kernel_size=(3,3), padding='same', activation='relu'))\n# model.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n#Fully connected\nmodel.add(Flatten())\nmodel.add(Dense(256,  activation = \"relu\"))\n\n#output layer\nmodel.add(Dense(num_classes, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.compile(loss='category_crossentropy',optimizer='adam',metrics=['accuracy'])\n\nmodel.compile(optimizer=\"adam\", loss='categorical_crossentropy', metrics=['categorical_accuracy'])\nprint (model.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_dir = './training_dataset'\n\nimg_height = 128\nimg_width = 128\nbatch_size = 512\nnb_epochs = 5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Training & Validation Dataset\n\n\ntrain_data_dir = training_dataset\n\ntrain_datagen = ImageDataGenerator(\n    rotation_range=40,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split=0.2) # set validation split\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_data_dir,\n    target_size=(img_height, img_width),\n    batch_size=batch_size,\n    class_mode='categorical',\n    shuffle = False,\n    subset='training') # set as training data\n\nvalidation_generator = train_datagen.flow_from_directory(\n    train_data_dir, # same directory as training data\n    target_size=(img_height, img_width),\n    batch_size=batch_size,\n    class_mode='categorical',\n    shuffle = False,\n    subset='validation') # set as validation data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntest_generator = train_datagen.flow_from_directory(test,\n                                              target_size = (img_height, img_width),\n                                              batch_size = batch_size,\n                                              class_mode = 'categorical',\n                                              shuffle = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nmodel.fit_generator(\n    train_generator,\n    steps_per_epoch = train_generator.samples // batch_size,\n    validation_data = validation_generator, \n    validation_steps = validation_generator.samples // batch_size,\n    epochs = nb_epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\npred_classes = train_generator.class_indices\npred_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Predicting\nprediction = model.predict(test_generator, test_generator.samples//batch_size)\nprediction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"key_list = list(pred_classes.keys())\nval_list = list(pred_classes.values())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_list","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_value = []\nfor p in prediction:\n    predicted_value.append(key_list[val_list.index(np.argmax(p))])\nprint(predicted_value[-10:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file_test = []\n\nfor files in test_generator.filenames:\n    file_test.append(files.split('/')[1].split('.')[0])\nprint(f\"File corresponding to prediction: {file_test[:10]} ...\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(file_test)):\n    df_submission.loc[df_submission.IMAGE == file_test[i]+\".jpg\", 'LABEL'] = int(predicted_value[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission.to_csv(\"submission.csv\", index=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}