{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Introduction\n* The Notebook is created on Dog Breed Dataset.\n* The Notebook helps you to move one step further in transfer learning.\n* As there are 120 Different Breeds of Dog present in the Dataset it becomes difficult for a single pretrained model to give Good results.\n* Here we used 3 different pretrained models to extract features from the images and combined them and then trained a DNN model on these features."},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = '../input/dog-breed-identification/train'\ntest_dir = '../input/dog-breed-identification/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_size = len(os.listdir('../input/dog-breed-identification/train'))\ntest_size = len(os.listdir('../input/dog-breed-identification/test'))\n\ntrain_size,test_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/dog-breed-identification/labels.csv')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extracting different classes\ndog_breeds = sorted(df['breed'].unique())\nn_classes = len(dog_breeds)\nprint(n_classes)\ndog_breeds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Converting classes to numbers\nclass_to_num = dict(zip(dog_breeds,range(n_classes)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Function to load and convert images to array\nfrom keras.preprocessing.image import load_img\nfrom keras.utils import to_categorical\n\ndef images_to_array(data_dir,df,image_size):\n    image_names = df['id']\n    image_labels = df['breed']\n    data_size = len(image_names)\n    \n    X = np.zeros([data_size,image_size[0],image_size[1],image_size[2]],dtype = np.uint8)\n    y = np.zeros([data_size,1],dtype = np.uint8)\n    \n    for i in range(data_size):\n        img_name = image_names[i]\n        img_dir = os.path.join(data_dir,img_name+'.jpg')\n        img_pixels = load_img(img_dir,target_size=image_size)\n        X[i] = img_pixels\n        y[i] = class_to_num[image_labels[i]]\n        \n    y = to_categorical(y)\n    \n    ind = np.random.permutation(data_size)\n    X = X[ind]\n    y = y[ind]\n    print('Ouptut Data Size: ', X.shape)\n    print('Ouptut Label Size: ', y.shape)\n    return X, y     ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Selecting image size according to pretrained models\nimg_size = (299,299,3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X, y = images_to_array(train_dir,df,img_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Extracting Features"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Function to extract features from images\nfrom keras.models import Model\nfrom keras.layers import BatchNormalization, Dense, GlobalAveragePooling2D,Lambda, Dropout, InputLayer, Input\n\ndef get_features(model_name, data_preprocessor, input_size, data):\n    #Prepare pipeline.\n    input_layer = Input(input_size)\n    preprocessor = Lambda(data_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    #Extract feature.\n    feature_maps = feature_extractor.predict(data, batch_size=32, verbose=1)\n    print('Feature maps shape: ', feature_maps.shape)\n    return feature_maps","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extracting features using InceptionV3\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extracting features using Xception\nfrom keras.applications.xception import Xception, preprocess_input\nxception_preprocessor = preprocess_input\nxception_features = get_features(Xception,\n                                 xception_preprocessor,\n                                 img_size, X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extracting features using InceptionResnetV2\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input\ninc_resnet_preprocessor = preprocess_input\ninc_resnet_features = get_features(InceptionResNetV2,\n                                   inc_resnet_preprocessor,\n                                   img_size, X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#concatinating features\nfinal_features = np.concatenate([inception_features,\n                                 xception_features,\n                                 inc_resnet_features,], axis=-1)\nprint('Final feature maps shape', final_features.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del X","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Building and training Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Callbacks\nfrom keras.callbacks import EarlyStopping\nEarlyStop_callback = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)\nmy_callback=[EarlyStop_callback]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Building Model\nfrom keras.models import Sequential\nmodel = Sequential()\nmodel.add(InputLayer(final_features.shape[1:]))\nmodel.add(Dropout(0.7))\nmodel.add(Dense(120,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Compiling Model\nmodel.compile(optimizer='adam',\n            loss='categorical_crossentropy',\n            metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Training Model\nhistory = model.fit(final_features,\n                  y,\n                  batch_size=32,\n                  epochs=50,\n                  validation_split=0.1,\n                  callbacks=my_callback)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading and Predicting test Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Converting test images to array\ndef images_to_array2(data_dir,df, img_size):\n    images_names = df['id']\n    data_size = len(images_names)\n    X = np.zeros([data_size, img_size[0], img_size[1], 3], dtype=np.uint8)\n    \n    for i in range(data_size):\n        image_name = images_names[i]\n        img_dir = os.path.join(data_dir, image_name+'.jpg')\n        img_pixels = load_img(img_dir, target_size=img_size)\n        X[i] = img_pixels\n        \n    print('Ouptut Data Size: ', X.shape)\n    return X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df = pd.read_csv('../input/dog-breed-identification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = images_to_array2(test_dir, sample_df, img_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extract test data features.\ninception_features = get_features(InceptionV3, inception_preprocessor, img_size, test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xception_features = get_features(Xception, xception_preprocessor, img_size, test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inc_resnet_features = get_features(InceptionResNetV2, inc_resnet_preprocessor, img_size, test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_features = np.concatenate([inception_features,\n                                 xception_features,\n                                 inc_resnet_features],axis=-1)\nprint('Final feature maps shape', test_features.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del test_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(test_features, batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for breed in dog_breeds:\n    sample_df[breed] = y_pred[:,class_to_num[breed]]\nsample_df.to_csv('pred.csv', index=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df.head()","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}