{"cells":[{"metadata":{},"cell_type":"markdown","source":"### References\n\nhttps://www.kaggle.com/socathie/pre-trained-mobilenetv2-1000-classes-1-epoch/output\n\nhttps://www.kaggle.com/renjithrrkj/land-mark/notebook"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.figure_factory as ff\nimport plotly.graph_objects as go\nfrom scipy import stats\nimport cv2\nimport glob\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import MobileNetV2\nfrom keras.utils import to_categorical\nfrom keras.layers import Dense\nfrom keras import Model\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model\nfrom tensorflow.keras.applications.xception import Xception\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\n\nimport tensorflow.keras.layers as L\nimport efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df=pd.read_csv('../input/landmark-recognition-2020/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"landmark_count=pd.value_counts(train_df[\"landmark_id\"])\nlandmark_count=landmark_count.reset_index()\nlandmark_count.rename(columns={\"index\":'landmark_ids','landmark_id':'count'},inplace=True)\nlandmark_count","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = landmark_count[0:50]\nsample.rename(columns={\"index\":'landmark_ids','landmark_id':'count'},inplace=True)\nsample.sort_values(by=['count'],ascending=False,inplace=True)\nsample['landmark_ids']=sample['landmark_ids'].map(str)\nsample.info()\nsample","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_list = glob.glob('../input/landmark-recognition-2020/train/*/*/*/*')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"example = cv2.imread(train_list[10])\nplt.imshow(example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[\"filename\"] = train_df.id.str[0]+\"/\"+train_df.id.str[1]+\"/\"+train_df.id.str[2]+\"/\"+train_df.id+\".jpg\"\ntrain_df[\"label\"] = train_df.landmark_id.astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from collections import Counter\n\nc = train_df.landmark_id.values\ncount = Counter(c).most_common(1000)\nprint(len(count), count[-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# only keep 3000 classes\nkeep_labels = [i[0] for i in count]\ntrain_keep = train_df[train_df.landmark_id.isin(keep_labels)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_rate = 0.2\nbatch_size = 32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = ImageDataGenerator(validation_split=val_rate)\n\ntrain_gen = gen.flow_from_dataframe(\n    train_keep,\n    directory=\"/kaggle/input/landmark-recognition-2020/train/\",\n    x_col=\"filename\",\n    y_col=\"label\",\n    weight_col=None,\n    target_size=(256, 256),\n    color_mode=\"rgb\",\n    classes=None,\n    class_mode=\"categorical\",\n    batch_size=batch_size,\n    shuffle=True,\n    subset=\"training\",\n    interpolation=\"nearest\",\n    validate_filenames=False)\n    \nval_gen = gen.flow_from_dataframe(\n    train_keep,\n    directory=\"/kaggle/input/landmark-recognition-2020/train/\",\n    x_col=\"filename\",\n    y_col=\"label\",\n    weight_col=None,\n    target_size=(256, 256),\n    color_mode=\"rgb\",\n    classes=None,\n    class_mode=\"categorical\",\n    batch_size=batch_size,\n    shuffle=True,\n    subset=\"validation\",\n    interpolation=\"nearest\",\n    validate_filenames=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([\n    efn.EfficientNetB2(\n        input_shape=(256, 256, 3),\n        weights='imagenet',\n        include_top=False\n    ),\n    L.GlobalAveragePooling2D(),\n    L.Dense(1000, activation='softmax')\n])\n\nmodel.compile(\n    optimizer='adam',\n    loss = 'categorical_crossentropy',\n    metrics=['categorical_accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# training parameters\nepochs = 5 # maximum number of epochs\ntrain_steps = int(len(train_keep)*(1-val_rate))//batch_size\nval_steps = int(len(train_keep)*val_rate)//batch_size\n\nmodel_checkpoint = ModelCheckpoint(\"model_efnB3.h5\", save_best_only=True, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_gen, steps_per_epoch=train_steps, epochs=epochs,validation_data=val_gen, validation_steps=val_steps, callbacks=[model_checkpoint])\n\nmodel.save(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv(\"/kaggle/input/landmark-recognition-2020/sample_submission.csv\")\nsub[\"filename\"] = sub.id.str[0]+\"/\"+sub.id.str[1]+\"/\"+sub.id.str[2]+\"/\"+sub.id+\".jpg\"\nsub","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_model = load_model(\"model_efnB3.h5\")\n\ntest_gen = ImageDataGenerator().flow_from_dataframe(\n    sub,\n    directory=\"/kaggle/input/landmark-recognition-2020/test/\",\n    x_col=\"filename\",\n    y_col=None,\n    weight_col=None,\n    target_size=(256, 256),\n    color_mode=\"rgb\",\n    classes=None,\n    class_mode=None,\n    batch_size=1,\n    shuffle=True,\n    subset=None,\n    interpolation=\"nearest\",\n    validate_filenames=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_one_hot = best_model.predict_generator(test_gen, verbose=1, steps=len(sub))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = np.argmax(y_pred_one_hot, axis=-1)\ny_prob = np.max(y_pred_one_hot, axis=-1)\nprint(y_pred.shape, y_prob.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_uniq = np.unique(train_keep.landmark_id.values)\n\ny_pred = [y_uniq[Y] for Y in y_pred]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(len(sub)):\n    sub.loc[i, \"landmarks\"] = str(y_pred[i])+\" \"+str(y_prob[i])\nsub = sub.drop(columns=\"filename\")\nsub.to_csv(\"submission.csv\", index=False)\nsub","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}