{"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":{"trusted":true},"cell_type":"code","source":"#extracting the data set \n#os.path.join (path1, path2, ... )\n#    os.path.join(path, *paths) Join one or more path components intelligently. \n#    The return value is the concatenation of path and any members of *paths \n#    with exactly one directory separator (os.sep) following each non-empty part except the last, \n#    meaning that the result will only end in a separator if the last part is empty. \n#    If a component is an absolute path, all previous components are thrown away and \n#    joining continues from the absolute path component.\n#    Example:\n#    os.path.join('/path', 'path1', 'path2')    # '/path/path1/path2'\n#    os.path.join('path', '/path1', 'path2')    # '/path1/path2'\n#    os.path.join('path', '/path1', 'path2','') # '/path1/path2/'\n\n\ninput_dir  = '/kaggle/input/dogs-vs-cats'\nwork_dir   = '/kaggle/working'\n\nimport zipfile\nwith zipfile.ZipFile( os.path.join(input_dir, 'train.zip'), 'r') as zip_ref:\n    zip_ref.extractall(work_dir)\n    zip_ref.close()\nwith zipfile.ZipFile( os.path.join(input_dir, 'test1.zip'), 'r') as zip_ref:\n    zip_ref.extractall(work_dir)\n    zip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#preparing the training set \n\ntrain_dir = os.path.join(work_dir,'train')\ntest_dir  = os.path.join(work_dir,'test1')\n\ntrain_dog = os.path.join(train_dir,'dog')\ntrain_cat = os.path.join(train_dir,'cat')\n\n#if the two directories had already been create, catch the error and print it\ntry:\n    os.mkdir(train_dog)    \nexcept OSError as error: \n    print(error) \ntry:\n    os.mkdir(train_cat)    \nexcept OSError as error: \n    print(error) \n\n\n#regex tools to identify filenames including 'cat'/'dog' strings\nfrom re import match,compile \n\n#I will use os.rename basically to implement the bash command mv \nfor file in os.listdir(train_dir):\n        if compile(r'dog\\.').match(file) : \n            old_position = os.path.join(train_dir,file)\n            new_position = os.path.join(train_dog,file)\n            os.rename(old_position,new_position) \n            \n        elif compile(r'cat\\.').match(file) : \n            old_position = os.path.join(train_dir,file)\n            new_position = os.path.join(train_cat,file)\n            os.rename(old_position,new_position)\n            \n        else :\n            print(file, 'this file was neither a dog. , nor a cat. .')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#to later check that ImageDataGenerator will work correctly \nprint('Number of dogs in training set :' , len (os.listdir(dog_train)))\nprint('Number of cats in training set :' , len (os.listdir(cat_train)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#let's give a look to 1 random cat and 1 random dog from training set \n%matplotlib inline\n\nimport matplotlib.image as mpimg #to read 3-channels images \nimport matplotlib.pyplot as plt  \nimport matplotlib.gridspec as gridspec\nimport random\n\nrandom_dog = random.randint(1,12500)\nrandom_cat = random.randint(1,12500)\nimg_dog = mpimg.imread( os.path.join(train_dog, 'dog.'+str(random_dog)+'.jpg') )\nimg_cat = mpimg.imread( os.path.join(train_cat, 'cat.'+str(random_cat)+'.jpg') )\n\n\n#for evantually using in papers:  single colum 8.8 , double column 18.\ndef cm2inch(cm):\n    \"\"\"Centimeters to inches\"\"\"\n    return cm *0.393701\n\nwidth   = 18.\nratio   = 2/3\nfig     = plt.figure(figsize=(cm2inch(width), cm2inch(width*ratio)))\ngs      = gridspec.GridSpec(nrows=1,ncols=2)\ndog_fig = fig.add_subplot(gs[0,0])\ncat_fig = fig.add_subplot(gs[0,1])\ndog_fig.set_title('dog id:'+str(random_dog))\ncat_fig.set_title('cat id:'+str(random_cat))\ndog_fig.imshow(img_dog)\ncat_fig.imshow(img_cat)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator( rescale = 1.0/255. )\ntest_datagen  = ImageDataGenerator( rescale = 1.0/255. )\n\ntrain = train_datagen.flow_from_directory(\n        train_dir,  \n        target_size=(300, 300),  \n        batch_size=250,\n        class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\n\nmodel = tf.keras.models.Sequential([\n    \n            #compressing down the 3D volume \n            #note that the depth is going with power of 2 \n            tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),\n            tf.keras.layers.MaxPooling2D(2,2),\n            tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n            tf.keras.layers.MaxPooling2D(2,2), \n            tf.keras.layers.Conv2D(64, (3,3), activation='relu'), \n            tf.keras.layers.MaxPooling2D(2,2),\n    \n            #flattening \n            tf.keras.layers.Flatten(),\n    \n            # 512 neuron hidden layer\n            tf.keras.layers.Dense(512, activation='relu'), \n            # Only 1 output neuron.\n            tf.keras.layers.Dense(1, activation='sigmoid') \n    \n    ])\n\nmodel.summary()\n\nplot_model(model,  show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class myCallback(tf.keras.callbacks.Callback):\n  def on_epoch_end(self, epoch, logs={}):  \n    if(logs.get('accuracy')>0.9):\n      print(\"\\nReached 90% accuracy so cancelling training!\")\n      self.model.stop_training = True\n        \ncallbacks = myCallback()\n\noptimizer = tf.keras.optimizers.Adam()\n\nmodel.compile(optimizer=optimizer,\n              loss='binary_crossentropy',\n              metrics = ['accuracy'])\n\nhistory = model.fit(train,\n                    steps_per_epoch=100,\n                    epochs=15,\n                    verbose=2,callbacks=[callbacks])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#now I will make prediction on the test set \nfrom keras.preprocessing import image\n#I will use \n#image.load_img   :   it has an option specifying the desired size of the input\n#                     note that the test images have different sizes. Our net has (300,300)\n\n\npredicted_val = []\nid_line = []\n\ni = 0\nfor im in os.listdir(test_dir):\n    \n    #Our net accepts input with shape of (300,300) \n    right_img = image.load_img(os.path.join(test_dir,im) , color_mode = 'rgb', target_size=(300,300))\n    \n    #need to have the shape (batch_size, 300,300, n° channels). batch_size = 1 as single example\n    #I am also normalising the features : image/255.\n    image_to_be_tested = np.expand_dims(image.img_to_array(right_img)/255.,axis=0)\n    pred = model.predict(image_to_be_tested)\n    pred = int(round(pred[0][0]))\n    predicted_val.append(pred)\n    \n    #regex expression to get the id of the image as a sequence of digits \\d+ followed by .\n    id_line.append( eval(re.compile('^\\d+(?=\\.)').search(im).group()) )\n    i+=1\n    \n    #lengthy process: I am keeping track of it in this way\n    if i == int(12500*0.25):\n        print('25% test set analysed')\n\n    if i == int(12500*0.5):\n        print('50% test set analysed')\n\n    if i == int(12500*0.75):\n        print('75% test set analysed')\n\n    if i == int(12500):\n        print('100% test set analysed')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = pd.DataFrame({'id':id_line, 'label':predicted_val})\nsubmission_df.to_csv(\"submission.csv\", index=False)\nsubmission_df","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}