{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nfrom datetime import datetime\nfrom collections import Counter\nimport json\nimport os\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dim = 256\ntrain_files = []\ntest_files = []\ncountry_file = ''\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        path = os.path.join(dirname, filename)\n        if 'train' in path:\n            train_files.append(path)\n        elif 'test' in path:\n            test_files.append(path)\n        elif 'json' in path:\n            country_file = path","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with open(country_file) as json_file:\n    tmp = json.load(json_file)\ncountry = {}\nfor key in tmp.keys():\n  country[int(key)] = tmp[key].split(',')[-1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_set = []\nfor f in train_files:\n  idx = int(f.split('/')[6])\n  train_set.append([f, country[idx]])\ntrain_set = pd.DataFrame(train_set, columns=['Image','Country'])\n    \ntest_set = []\nfor f in test_files:\n    test_set.append(f)\ntest_set = pd.DataFrame(test_set, columns=['Image'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_gen = ImageDataGenerator(rescale = 1./255,\n                                    shear_range = 0.2,\n                                    zoom_range = 0.2,\n                                    horizontal_flip = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_data_gen.flow_from_dataframe(\n    dataframe = train_set,\n    directory=\"\",\n    x_col=\"Image\",\n    y_col=\"Country\",\n    class_mode=\"categorical\",\n    target_size=(dim,dim),\n    batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes = len(Counter(train_generator.classes).keys())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier = Sequential()\nclassifier.add(Conv2D(filters = 32, kernel_size = (3,3), activation = 'relu', input_shape = (dim,dim,3)))\nclassifier.add(MaxPool2D(pool_size = (2,2)))\nclassifier.add(Conv2D(64,(3,3),activation = 'relu'))\nclassifier.add(Conv2D(64,(3,3),activation = 'relu'))\nclassifier.add(MaxPool2D(pool_size = (2,2)))\nclassifier.add(Conv2D(128,(3,3),activation = 'relu'))\nclassifier.add(Conv2D(128,(3,3),activation = 'relu'))\nclassifier.add(MaxPool2D(pool_size = (2,2)))\nclassifier.add(Flatten())\nclassifier.add(Dense(units = 128, activation = 'relu'))\nclassifier.add(Dense(units = 128, activation = 'relu'))\nclassifier.add(Dense(units = num_classes , activation = 'softmax'))\nclassifier.compile(\n    optimizer = 'adam', \n    loss = 'categorical_crossentropy', \n    metrics = ['categorical_accuracy','accuracy']\n)\nclassifier.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier.fit_generator(train_generator, epochs = 100, steps_per_epoch = 70)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = train_generator.class_indices\nprint(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inverted_classes = dict(map(reversed, classes.items()))\nprint(inverted_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\n\nY_pred = []\n\nfor idx in range(test_set.shape[0]):\n  img = image.load_img(path=test_set['Image'][idx],target_size=(dim,dim,3))\n  img = image.img_to_array(img)\n  test_img = img.reshape((1,dim,dim,3))\n  img_class = classifier.predict_classes(test_img)\n  prediction = img_class[0]\n  Y_pred.append(prediction)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(Y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction_classes = [ inverted_classes.get(item,item) for item in Y_pred ]\nprint(prediction_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\nfor idx in range(test_set.shape[0]):\n    predictions.append([test_set['Image'][idx].split('/')[6].split('.')[0],prediction_classes[idx]])\npredictions = pd.DataFrame(predictions, columns=['ID','Country'])\npredictions['ID'] = predictions['ID'].astype(int)\npredictions.sort_values(by=['ID'], inplace=True)\npredictions.to_csv(datetime.now().strftime(\"gallivanters_%Y%m%d_%H%M%S.csv\"), index=False)\npredictions.head(20)","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}