{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport shutil\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"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 in \n\n# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**First we organise the labels**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# dict_labels={}\nlabel_csv = pd.read_csv(\"/kaggle/input/dog-breed-identification/labels.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = label_csv.iloc[:, 0].values\nY = label_csv.iloc[:, 1].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#____________________________________--","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"breeds = list(sorted(set(Y)))\nos.mkdir(\"/kaggle/working/training/\")\nfor i in breeds:\n    os.mkdir(\"/kaggle/working/training/\" + i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_paths = label_csv.assign(img_path = lambda x: \"/kaggle/input/dog-breed-identification/train/\" + x[\"id\"] + \".jpg\")\nfor i in range(10222):\n    shutil.copyfile(label_paths['img_path'][i], \"/kaggle/working/training/\" + label_paths['breed'][i] + \"/\" + label_paths['id'][i] + \".jpg\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.inception_v3 import InceptionV3\npre_trained_model = InceptionV3(input_shape = (150,150, 3), include_top = False, weights = 'imagenet')\nfor layer in pre_trained_model.layers:\n    layer.trainable = False\npre_trained_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"last_layer = pre_trained_model.get_layer('mixed7')\nlast_output = last_layer.output\nprint(last_output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class mcb(tf.keras.callbacks.Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if logs['acc']>0.99:\n            print(\"\\nReached 99% accuracy\\n\")\n            self.model.stop_training = True\ncallbacks = mcb()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow import keras\nimport tensorflow as tf\nx = tf.keras.layers.Flatten()(last_output)\nx = tf.keras.layers.Dense(1024, activation = 'relu')(x)\nx = tf.keras.layers.Dense(120, activation = 'softmax')(x)\nmodel = tf.keras.Model(pre_trained_model.input, x)\nmodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#_______________________________","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(tf.version)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n    rescale =1.0/ 255.0\n)\ntrain_generator = train_datagen.flow_from_directory(\n    \"/kaggle/working/training\",\n    target_size = (150,150),\n    batch_size = 19,\n    class_mode = 'categorical'\n)\ntest_datagen = ImageDataGenerator(\n    rescale = 1.0/ 255.0\n)\nfmodelt = model.fit_generator(train_generator, epochs =10, steps_per_epoch = len(train_generator), callbacks = [callbacks])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.image  as mpimg\nimport matplotlib.pyplot as plt\nacc = fmodelt.history['acc']\nloss = fmodelt.history['loss']\nepochs = range(len(acc))\nplt.plot(epochs,acc, 'r', label = \"Training_accuracy\")\nplt.legend(loc = \"lower right\")\nplt.figure()\nplt.plot(epochs, loss, 'b', label = \"Training_loss\")\nplt.title(\"Training accuracy and loss\")\nplt.legend(loc=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir(\"/kaggle/working/testing/\")\nos.mkdir(\"/kaggle/working/testing/test\")\nfor i in os.listdir(\"/kaggle/input/dog-breed-identification/test/\"):\n    shutil.copyfile(\"/kaggle/input/dog-breed-identification/test/\" + i, \"/kaggle/working/testing/test/\"+ i)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1.0/ 255.0)\ntest_generator = test_datagen.flow_from_directory(\n    \"/kaggle/working/testing/\",\n    target_size = (150,150),\n    class_mode = 'categorical',\n    shuffle=False\n)\npreds = model.predict(test_generator, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds[0].round(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ids=[]\nfor i in os.listdir(\"/kaggle/working/testing/test/\"):\n    ids.append(i[:-4])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sol = pd.DataFrame(preds.round(4))\nsol.columns = breeds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sol.insert(0, 'id', ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sol.to_csv(\"Dog_breed_classifier.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":4}