{"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\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\ndf_label = pd.read_csv(\"../input/dog-breed-identification/labels.csv\")\ndf_label.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_label.shape\ndf_label['breed'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_name = df_label['breed'].sort_values().unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_label.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\nencoder = LabelEncoder()\nencoder.fit(df_label['breed'])\ndf_label['breed'] = encoder.transform(df_label['breed'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoder.inverse_transform([19,37])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_label['id'] = df_label['id'] + '.jpg'\ndf_label.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_label['breed'] = df_label['breed'].astype(str)\ndf_label.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator ( \n    rescale =1/255.,\n    rotation_range = 20,\n    width_shift_range = 0.1,\n    height_shift_range =0.1,\n    shear_range = 0.1,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    fill_mode = 'nearest',\n    validation_split=0.2\n)\n\nval_datagen = ImageDataGenerator ( \n    rescale=1/255. ,\n    validation_split=0.2\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATASET_DIR = '/kaggle/input/dog-breed-identification'\ntrain_dir = '/kaggle/input/dog-breed-identification/train'\ntest_dir = '/kaggle/input/dog-breed-identification/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe (\n    dataframe = df_label,\n    directory = train_dir,\n    x_col = 'id' ,     \n    y_col = 'breed',      \n    target_size = (150,150),\n    batch_size = 128,\n    class_mode = 'categorical',\n    subset = 'training' ,\n    seed = 7   \n)\nval_generator = val_datagen.flow_from_dataframe (\n    dataframe = df_label,\n    directory = train_dir,\n    x_col = 'id' ,     \n    y_col = 'breed',      \n    target_size = (150,150),\n    batch_size = 128,\n    class_mode = 'categorical',\n    subset = 'validation' ,\n    seed = 7   \n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers,models ,optimizers\nmodel = tf.keras.Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(120, activation='softmax'))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',optimizer='rmsprop',metrics=['accuracy'])\nhistory = model.fit(train_generator,\n                    epochs=1,\n                    steps_per_epoch=len(train_generator)-1,\n                    validation_data=val_generator,\n                    validation_steps=len(val_generator)-1\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = '../input/dog-breed-identification'\ntest_datagen = ImageDataGenerator (\nrescale = 1/255,\n)\n\ntest_generator = test_datagen.flow_from_directory (\n    base_dir,\n    target_size = (150,150),\n    batch_size = 128,\n    classes=['test']\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict(test_generator,batch_size=len(test_generator)-1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission = pd.read_csv('../input/dog-breed-identification/sample_submission.csv')\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_to_num = dict(zip(label_name, range(120)))  \nfor name in label_name:  \n    df_submission[name] = preds[:,class_to_num[name]]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission[name].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_submission.to_csv('submission_dog_cnn.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}