{"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\n\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir(r'/kaggle/input/humpback-whale-identification')\npath=os.getcwd()\nprint(path)\nprint(os.listdir())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_train=os.path.join(path,\"train\")\nprint(\"train_path: \"+path_train)\npath_test=os.path.join(path,\"test\")\nprint(\"train_path: \"+path_test)\npath_train_csv=os.path.join(path,\"train.csv\")\nprint(\"train_path: \"+path_train_csv)\npath_sample_csv=os.path.join(path,\"sample_submission.csv\")\nprint(\"train_path: \"+path_sample_csv)\nroot_path = '/kaggle/input'\nos.mkdir(os.path.join(root_path,\"Train_new\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir(r'/kaggle/input')\npath=os.getcwd()\nprint(path)\nprint(os.listdir())\nos.chdir(r'/kaggle/input/Train_new')\npath_Train_new=os.getcwd()\nprint(path_Train_new)\n                         \n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv(path_train_csv)\nprint(train.head(3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a=train['Id'].value_counts()\nb=train['Image'].value_counts()\nprint(\"Unique Id: \"+str(len(a)))\nprint(\"total images: \"+str(len(b)))\nprint(\"train_shape: \"+str(train.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.preprocessing.image import ImageDataGenerator\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# filtering images w.r.t ID\nlabel=train['Id'].unique()\nprint(\"Classes: \"+str(len(label)))\nd={}\nfor name in label:\n    index=train['Id']==name\n    a=train[index]\n    d[name]=a['Image'].tolist()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"root_path = path_Train_new\nfor file in label:\n    os.mkdir(os.path.join(root_path,file))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# copying images to their respected ID's\nos.chdir(path_train)\nimport shutil\nfor name in label:\n    list=d[name]\n    for f in list:\n        path=os.path.join(path_Train_new,name)\n        shutil.copy(f,path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras import applications\nfrom keras.layers import Dense\nfrom keras.models import Model\nfrom keras.models import load_model\nfrom keras import Sequential\nfrom keras.layers.convolutional import Conv2D,MaxPooling2D\nfrom keras.layers import Flatten","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir(r'/kaggle/input/mobilenet')\nmobile=load_model(\"MobileNet.h5\")\nmobile.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=mobile.layers[-6].output\np=Dense(5005,activation='softmax')(x)\nmodel=Model(inputs=mobile.input,outputs=p)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in model.layers[:-15]:\n    layer.trainable=False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom sklearn.metrics import confusion_matrix\nfrom keras.preprocessing.image import ImageDataGenerator\nimport tensorflow as tf\nclass myCallback(tf.keras.callbacks.Callback):\n    def on_epoch_end(self,epoch,logs={}):\n        if(logs.get('val_accuracy')>0.90):\n            print('cancelling since validation accuracy has been reached to 90%')\n            self.model.stop_training=True\ncallbacks_3=myCallback()   \nimport tensorflow as tf\n \ntrain_gen=ImageDataGenerator(rescale=1/255,rotation_range=40,width_shift_range=0.3,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2\n                            ,fill_mode='nearest',validation_split=0.06)\ntrain_data=train_gen.flow_from_directory(path_Train_new,target_size=(224,224),batch_size=50,subset='training')\nvalidation_data=train_gen.flow_from_directory(path_Train_new,target_size=(224,224),batch_size=10,subset='validation')\nmodel.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])\nmodel.fit_generator(train_data,epochs=10,validation_data=validation_data)\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir('/kaggle/working')\nmodel.save(\"Whale01.h5\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\ntrain=pd.read_csv(path_train_csv)\ntrain_images=train['Image'].to_list()\n    \ny_pred=[]\nfor file in train_images:\n    path_file=os.path.join(path_train,file)\n    img=image.load_img(path_file,target_size=(224,224))\n    img=image.img_to_array(img)\n    img=np.expand_dims(img,axis=0)\n    y_pred.append(model.predict(img))\ny_pred_np=np.array(y_pred)\ny_pred_np=y_pred_np.reshape(25361,5005)\ny_pred_final=y_pred_np.argmax(axis=1)\ntrain_labels=train['Id']\ntrain_labels.replace({'Large':0,'Small':1},inplace=True)\n\n\n         \n            \n  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images=os.listdir(path_test)\nprint(len(test_images))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ny_pred_test=[]\n\nfor file in test_images:\n    path_file=os.path.join(path_test,file)\n    img=image.load_img(path_file,target_size=(224,224))\n    img=image.img_to_array(img)\n    img=np.expand_dims(img,axis=0)\n    y_pred.append(model.predict(img))\ny_pred_np=np.array(y_pred)\ny_pred_np=y_pred_np.reshape(7960,5005)\ny_pred_final=y_pred_np.argmax(axis=1)\ntrain_labels=train['Id']\ntrain_labels.replace({'Large':0,'Small':1},inplace=True)\n\n\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":1}