{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd \n\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.autonotebook import tqdm\n\nimport tensorflow as tf\nfrom keras import Sequential\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers import Flatten,Dense,BatchNormalization,Activation,Dropout\nfrom keras.layers import Lambda, Input, GlobalAveragePooling2D,BatchNormalization\nfrom keras.utils import to_categorical\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.image import load_img","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:05:08.619256Z","iopub.execute_input":"2023-08-13T18:05:08.619769Z","iopub.status.idle":"2023-08-13T18:05:18.267671Z","shell.execute_reply.started":"2023-08-13T18:05:08.619733Z","shell.execute_reply":"2023-08-13T18:05:18.266719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:05:18.269479Z","iopub.execute_input":"2023-08-13T18:05:18.270257Z","iopub.status.idle":"2023-08-13T18:05:18.310774Z","shell.execute_reply.started":"2023-08-13T18:05:18.270220Z","shell.execute_reply":"2023-08-13T18:05:18.309851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nclasses = sorted(list(set(labels['breed'])))\nn_classes = len(classes)\nprint('Total unique breed {}'.format(n_classes))\n\n\n\nclass_to_num = dict(zip(classes, range(n_classes)))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:05:18.311894Z","iopub.execute_input":"2023-08-13T18:05:18.312658Z","iopub.status.idle":"2023-08-13T18:05:18.321499Z","shell.execute_reply.started":"2023-08-13T18:05:18.312627Z","shell.execute_reply":"2023-08-13T18:05:18.320591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (331,331,3)\n\ndef images_to_array(directory, label_dataframe, target_size = input_shape):\n    \n    image_labels = label_dataframe['breed']\n    images = np.zeros([len(label_dataframe), target_size[0], target_size[1], target_size[2]],dtype=np.uint8) #as we have huge data and limited ram memory. uint8 takes less memory\n    y = np.zeros([len(label_dataframe),1],dtype = np.uint8)\n    \n    for ix, image_name in enumerate(tqdm(label_dataframe['id'].values)):\n        img_dir = os.path.join(directory, image_name + '.jpg')\n        img = load_img(img_dir, target_size = target_size)\n        images[ix] = img\n        del img\n        \n        dog_breed = image_labels[ix]\n        y[ix] = class_to_num[dog_breed]\n    \n    y = to_categorical(y)\n    \n    return images, y","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:05:18.324394Z","iopub.execute_input":"2023-08-13T18:05:18.325415Z","iopub.status.idle":"2023-08-13T18:05:18.333880Z","shell.execute_reply.started":"2023-08-13T18:05:18.325370Z","shell.execute_reply":"2023-08-13T18:05:18.332988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time \nt = time.time()\n\nX, y = images_to_array('/kaggle/input/dog-breed-identification/train', labels[:])\n\nprint('runtime in seconds: {}'.format(time.time() - t))","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:05:18.335278Z","iopub.execute_input":"2023-08-13T18:05:18.335641Z","iopub.status.idle":"2023-08-13T18:06:43.149896Z","shell.execute_reply.started":"2023-08-13T18:05:18.335610Z","shell.execute_reply":"2023-08-13T18:06:43.148904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nlrr= ReduceLROnPlateau(monitor='val_acc', factor=.01, patience=3, min_lr=1e-5,verbose = 1)\n\n\nEarlyStop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:06:43.151332Z","iopub.execute_input":"2023-08-13T18:06:43.151805Z","iopub.status.idle":"2023-08-13T18:06:43.158078Z","shell.execute_reply.started":"2023-08-13T18:06:43.151769Z","shell.execute_reply":"2023-08-13T18:06:43.156903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nbatch_size= 128\nepochs=100\nlearn_rate=.001\nsgd=SGD(learning_rate=learn_rate, momentum=0.9, nesterov=False)\nadam=Adam(learning_rate=learn_rate, beta_1=0.9, beta_2=0.999, epsilon=None,  amsgrad=False)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:06:43.159315Z","iopub.execute_input":"2023-08-13T18:06:43.160267Z","iopub.status.idle":"2023-08-13T18:06:43.186155Z","shell.execute_reply.started":"2023-08-13T18:06:43.160232Z","shell.execute_reply":"2023-08-13T18:06:43.185324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimg_size = (331,331,3)\n\ndef get_features(model_name, model_preprocessor, input_size, data):\n\n    input_layer = Input(input_size)\n    preprocessor = Lambda(model_preprocessor)(input_layer)\n    base_model = model_name(weights='imagenet', include_top=False,\n                            input_shape=input_size)(preprocessor)\n    avg = GlobalAveragePooling2D()(base_model)\n    feature_extractor = Model(inputs = input_layer, outputs = avg)\n    \n    #Extract feature.\n    feature_maps = feature_extractor.predict(data, verbose=1)\n    print('Feature maps shape: ', feature_maps.shape)\n    return feature_maps","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:06:43.188966Z","iopub.execute_input":"2023-08-13T18:06:43.189228Z","iopub.status.idle":"2023-08-13T18:06:43.197544Z","shell.execute_reply.started":"2023-08-13T18:06:43.189207Z","shell.execute_reply":"2023-08-13T18:06:43.196679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\ninception_preprocessor = preprocess_input\ninception_features = get_features(InceptionV3,\n                                  inception_preprocessor,\n                                  img_size, X)\n\nprint('Inception feature maps shape', inception_features.shape)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:06:43.199574Z","iopub.execute_input":"2023-08-13T18:06:43.200528Z","iopub.status.idle":"2023-08-13T18:07:38.131564Z","shell.execute_reply.started":"2023-08-13T18:06:43.200499Z","shell.execute_reply":"2023-08-13T18:07:38.130478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nmodel = Sequential()\n# model.add(Dense(1028,input_shape=(final_features.shape[1],)))\nmodel.add(Dropout(0.7,input_shape=(inception_features.shape[1],)))\nmodel.add(Dense(n_classes,activation= 'softmax'))\n\nmodel.compile(optimizer=adam,\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n#Training the model. \nhistory = model.fit(inception_features, y,\n            batch_size=batch_size,\n            epochs=epochs,\n            validation_split=0.2,\n            callbacks=[lrr, EarlyStop])","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2023-08-13T18:07:38.135180Z","iopub.execute_input":"2023-08-13T18:07:38.135529Z","iopub.status.idle":"2023-08-13T18:07:47.333786Z","shell.execute_reply.started":"2023-08-13T18:07:38.135502Z","shell.execute_reply":"2023-08-13T18:07:47.332836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ndef images_to_array_test(test_path, img_size = (331,331,3)):\n    test_filenames = [test_path + fname for fname in os.listdir(test_path)]\n    data_size = len(test_filenames)\n    images = np.zeros([data_size, img_size[0], img_size[1], 3], dtype=np.uint8)\n        \n    for ix,img_dir in enumerate(tqdm(test_filenames)):\n        img = load_img(img_dir, target_size = img_size)\n        images[ix]=img\n        del img\n    print('Ouptut Data Size: ', images.shape)\n    return images\n\ntest_data = images_to_array_test('/kaggle/input/dog-breed-identification/test/', img_size)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:07:47.335443Z","iopub.execute_input":"2023-08-13T18:07:47.335783Z","iopub.status.idle":"2023-08-13T18:09:11.691296Z","shell.execute_reply.started":"2023-08-13T18:07:47.335750Z","shell.execute_reply":"2023-08-13T18:09:11.690321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef extact_features(data):\n    inception_features = get_features(InceptionV3, inception_preprocessor, img_size, data)\n    print('Inception feature maps shape', inception_features.shape)\n    return inception_features\n\ntest_features = extact_features(test_data)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:09:11.694173Z","iopub.execute_input":"2023-08-13T18:09:11.694837Z","iopub.status.idle":"2023-08-13T18:09:48.792108Z","shell.execute_reply.started":"2023-08-13T18:09:11.694803Z","shell.execute_reply":"2023-08-13T18:09:48.791031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = model.predict(test_features)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:09:48.793738Z","iopub.execute_input":"2023-08-13T18:09:48.794073Z","iopub.status.idle":"2023-08-13T18:09:49.653367Z","shell.execute_reply.started":"2023-08-13T18:09:48.794047Z","shell.execute_reply":"2023-08-13T18:09:49.652418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\npreds_df = pd.DataFrame(columns=[\"id\"] + list(classes))\n\ntest_path = \"/kaggle/input/dog-breed-identification/test/\"\npreds_df[\"id\"] = [os.path.splitext(path)[0] for path in os.listdir(test_path)]\npreds_df.loc[:,list(classes)] = pred\n\npreds_df.to_csv('submission.csv',index=None)","metadata":{"execution":{"iopub.status.busy":"2023-08-13T18:09:49.654969Z","iopub.execute_input":"2023-08-13T18:09:49.655311Z","iopub.status.idle":"2023-08-13T18:09:53.390794Z","shell.execute_reply.started":"2023-08-13T18:09:49.655280Z","shell.execute_reply":"2023-08-13T18:09:53.389759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}