{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os, cv2, random, time, shutil\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom tqdm import tqdm\nnp.random.seed(42)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\n%matplotlib inline \n\nimport keras\nfrom keras import backend\nfrom keras.applications.inception_v3 import InceptionV3,preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import SGD\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Set some directories\ntrain_zip_dir = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\ntest_zip_dir = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\nextract_dir = '/kaggle/working/extracted_data'\ntrain_dir = '/kaggle/working/train'\ntest_dir = '/kaggle/working/test'\nos.makedirs(train_dir+'/dog', exist_ok=True)\nos.makedirs(train_dir+'/cat', exist_ok=True)\nos.makedirs(test_dir+'/test_data', exist_ok=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extract data files\nimport zipfile\nwith zipfile.ZipFile(train_zip_dir, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)\n\nwith zipfile.ZipFile(test_zip_dir, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Function to move the images tp their corresponding folders:\ndef move_files(train_path,test_path):\n    print('Moving Training Files ..')\n    time.sleep(1)\n    for i in tqdm(os.listdir(train_path)):        \n        if 'dog' in i:\n            shutil.copyfile(train_path+i,train_dir+'/dog/'+i )\n        elif 'cat' in i:\n            shutil.copyfile(train_path+i,train_dir+'/cat/'+i )\n        else:\n            print('unkown File', i)\n            \n    print('Moving Testing Files ..')\n    time.sleep(1)\n    for i in tqdm(os.listdir(test_path)):                \n        shutil.copyfile(test_path+i, test_dir+'/test_data/'+i)\n    #Delete original data    \n    shutil.rmtree(extract_dir)\n        \nmove_files(extract_dir+'/train/', extract_dir+'/test/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get count of number of files in this folder and all subfolders\ndef get_num_files(path):\n    if not os.path.exists(path):\n        return 0\n    return sum([len(files) for r, d, files in os.walk(path)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Setting Image and model parameters\nImage_width,Image_height = 299,299\nbatch_size=64\ntotal_samples = get_num_files(train_dir)\nval_split=0.2\nn_train=total_samples*(1-val_split)\nn_val=total_samples*val_split\nnum_classes = 2\nprint(n_train,n_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define data pre-processing \ntrain_image_gen = ImageDataGenerator(rescale=1/255,horizontal_flip=True,validation_split=val_split)\n#Data loader to load each batch on the RAM at each step.\ntrain_generator = train_image_gen.flow_from_directory(train_dir,target_size=(Image_width,Image_height),\n                                                      batch_size=batch_size,seed=42,subset='training',\n                                                      shuffle=True,class_mode='categorical')\nval_generator = train_image_gen.flow_from_directory(train_dir,target_size=(Image_width,Image_height),\n                                                    batch_size=batch_size,seed=42,subset='validation',\n                                                    shuffle=True,class_mode='categorical')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping,ModelCheckpoint,TensorBoard\n#Prepare call backs\nLR_callback = keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', patience=3, verbose=2, factor=.5, min_lr=.00001)\nEarlyStop_callback = keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=7, restore_best_weights=True)\nmy_callback=[EarlyStop_callback, LR_callback]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Prepare the model.\nInceptionV3_base_model = InceptionV3(weights='imagenet', include_top=False)\nx = InceptionV3_base_model.output\nx_pool = GlobalAveragePooling2D()(x)\nfinal_pred = Dense(num_classes,activation='softmax')(x_pool)\nmodel = Model(inputs=InceptionV3_base_model.input,outputs=final_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Freeze frist 276 layer of the network which is 311 layer.\n#Freeze low and mid level feature extractors which represented in earlier layers.\nlayer_to_Freeze=276    \nfor layer in model.layers[:layer_to_Freeze]:\n    layer.trainable =False\nfor layer in model.layers[layer_to_Freeze:]:\n    layer.trainable=True\n\nsgd = SGD(lr = 0.01, decay = 1e-6, momentum = 0.9, nesterov = True)\nmodel.compile(optimizer=sgd,loss='binary_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Training ...\nhistory_transfer_learning = model.fit_generator(train_generator,epochs=30,\n                                                steps_per_epoch=n_train//batch_size,\n                                                validation_data=val_generator,\n                                                validation_steps=n_val//batch_size,\n                                                verbose=1,\n                                                callbacks=my_callback,\n                                                class_weight='auto')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Use Evaluate() or evalute_generator() to check your model accuracy on validation set.\nscore = model.evaluate_generator(val_generator,verbose=1)\nprint('Test loss: ', score[0])\nprint('Test accuracy', score[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define data pre-processing \ntest_image_gen = ImageDataGenerator(rescale=1/255)\ntest_generator = test_image_gen.flow_from_directory(test_dir,target_size=(Image_width,Image_height),batch_size=1,seed=42,class_mode=None,shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test_generator.reset()\ny_pred = model.predict_generator(generator=test_generator,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({'id':pd.Series(test_generator.filenames),'label':pd.Series(y_pred.clip(min=0.02,max=0.98)[:,1])})\nsubmission['id'] = submission.id.str.extract('(\\d+)')\nsubmission['id']=pd.to_numeric(submission['id'])\nsubmission.to_csv(\"MySubmission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#submission.nunique(axis=0)\nsubmission.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('DogVsCats_submission.csv',index=False)\n#Delete data files form output directory for commiting issues.\nshutil.rmtree(train_dir)\nshutil.rmtree(test_dir)","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}