{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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\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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"!pwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_folder = \"/kaggle/input/dog-breed-identification/train/\"\nimages_csv = \"/kaggle/input/dog-breed-identification/labels.csv\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nlen(os.listdir(images_folder))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np \nimport cv2\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport seaborn as sns\nsns.set()\ndf = pd.read_csv(images_csv)\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.breed.nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20, 4))\ndf.breed.value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fav_dogs = df.breed.value_counts()[:10].index.tolist()\nfav_dogs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fav_dog_df = df.loc[df.breed.isin(fav_dogs)]\nfav_dog_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fav_dog_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(cv2.imread(images_folder + fav_dog_df.loc[57, \"id\"] + \".jpg\").shape)\nprint(cv2.imread(images_folder + fav_dog_df.loc[70, \"id\"] + \".jpg\").shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nImage.open(images_folder + fav_dog_df.loc[57, \"id\"] + \".jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"from tqdm import tqdm_notebook\nimage_list = []\nlabel_list = []\n\nfor i in tqdm_notebook(fav_dog_df.itertuples()):\n    #print(i[1], i[2])\n    image = cv2.imread(images_folder + i[1] + \".jpg\")\n    image = cv2.resize(image, (300, 300))\n    image_list.append(image)\n    label_list.append(i[2])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(image_list), len(label_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = np.array(image_list)\ndel image_list","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.shape #Number of images, H, W, C","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y = pd.get_dummies(label_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\ntf.__version__","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Conv2D, MaxPooling2D, Dropout\nfrom tensorflow.keras.activations import relu, softmax\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom tensorflow.keras.optimizers import SGD\n# from tensorflow.keras.metrics import ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3,3), activation=relu, input_shape=(300,300,3)))\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Conv2D(32, kernel_size=(3,3), activation=relu))\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Conv2D(64, kernel_size=(3,3), activation=relu))\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(64, activation=relu))\nmodel.add(Dropout(0.2))  #neurons ignored to avoid overfitting\nmodel.add(Dense(10, activation=softmax))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nmodel.compile(loss=categorical_crossentropy, optimizer=SGD(), metrics=[\"acc\"])\n#model.compile(loss=categorical_crossentropy, optimizer=\"rmsprop\", metrics=[\"acc\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train, x_test, y_train, y_test = train_test_split(X,Y, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train.shape, x_test.shape, y_train.shape, y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%reload_ext tensorboard\ntbcallbk=tf.keras.callbacks.TensorBoard()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"StopMonitor = tf.keras.callbacks.EarlyStopping(monitor = \"val_loss\", mode=\"min\", verbose=1)\n%tensorboard --logdir logs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_history = model.fit(x_train,y_train,epochs=10, batch_size=32, validation_split=0.1)\n#model_history = model.fit(x_train,y_train,epochs=10, batch_size=32, validation_split=0.1,callbacks=[tbcallbk,StopMonitor])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#del model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_history.history.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(model_history.history[\"loss\"])\nplt.plot(model_history.history[\"val_loss\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(model.history.history[\"acc\"])\nplt.plot(model.history.history[\"val_acc\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"dog-breed-identification.model\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! mkdir -p save_model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.to_json())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#prediction start\n","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}