{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip -d train","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.models import Sequential\nimport matplotlib.pyplot as plt\nimport cv2\nimport pickle\nfrom sklearn.model_selection import train_test_split\nimport os, os.path, shutil\nimport numpy as np\nimport random\nfrom skimage import io \nfrom skimage.transform import rotate, AffineTransform, warp\nfrom skimage import img_as_ubyte\nfrom skimage.util import random_noise\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def anticlockwise_rotation(image):\n    angle= random.randint(0,180)\n    return rotate(image, angle)\n\ndef clockwise_rotation(image):\n    angle= random.randint(0,180)\n    return rotate(image, -angle)\n\ndef h_flip(image):\n    return  np.fliplr(image)\n\ndef v_flip(image):\n    return np.flipud(image)\n\ndef add_noise(image):\n    return random_noise(image)\n\ndef blur_image(image):\n    return cv2.GaussianBlur(image, (9,9),0)\n\ntransformations = {'rotate anticlockwise': anticlockwise_rotation,\n                      'rotate clockwise': clockwise_rotation,\n                      'horizontal flip': h_flip, \n                      'vertical flip': v_flip,\n                   'adding noise': add_noise,\n                   'blurring image':blur_image\n                 } ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_path=\"../working/train/train\" \nimages=[] # to store paths of images from folder","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfor im in os.listdir(images_path):  # read image name from folder and append its path into \"images\" array     \n    images.append(os.path.join(images_path,im))\n\n    \n\nimages_to_generate=1300  #you can change this value according to your requirement\ni=300                       # variable to iterate till images_to_generate\n\nwhile i<=images_to_generate:    \n    image=random.choice(images)\n    original_image = io.imread(image)\n    transformed_image=None\n#     print(i)\n    n = 0       #variable to iterate till number of transformation to apply\n    transformation_count = random.randint(1, len(transformations)) #choose random number of transformation to apply on the image\n    \n    while n <= transformation_count:\n        key = random.choice(list(transformations)) #randomly choosing method to call\n        transformed_image = transformations[key](original_image)\n        n = n + 1\n    \n    secondary_new_image_path = str(image[23:26] + str(i) + \".jpg\") ### cv2.imwrite DOES NOT LIKE a \".\" except at the end\n    new_image_path= images_path + \"/\" + secondary_new_image_path\n    print(new_image_path)\n    transformed_image = img_as_ubyte(transformed_image)  #Convert an image to unsigned byte format, with values in [0, 255].\n    transformed_image=cv2.cvtColor(transformed_image, cv2.COLOR_BGR2RGB) #convert image to RGB before saving it\n    cv2.imwrite(new_image_path, transformed_image) # save transformed image to path\n\n    i =i+1\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nimport os\n\npath, dirs, files = next(os.walk(\"../working/train/train\"))\nprint(len(files))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"### Sorting into different folders\npath = \"../working/train/train\"\nimages = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\n\nfor image in images:\n    folder_name = image[0:3]\n\n    new_path = os.path.join(path, folder_name)\n    if not os.path.exists(new_path):\n        os.makedirs(new_path)\n\n    old_image_path = os.path.join(path, image)\n    new_image_path = os.path.join(new_path, image)\n    shutil.move(old_image_path, new_image_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\npath, dirs, files = next(os.walk(\"../working/train/train\"))\nfile_count = len(files)\nprint(file_count)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = '/kaggle/working/train/train'\ncatagories = os.listdir(path)\nprint(catagories)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X =[]\ny = []\n\ndef create_data(img_size):\n    for c in catagories:\n        curr_path = os.path.join(path, c)\n        classification = catagories.index(c)\n        print(classification)\n        for img in os.listdir(curr_path):\n            try:\n                img_array = cv2.imread(os.path.join(curr_path, img), cv2.IMREAD_GRAYSCALE)\n                new_array = cv2.resize(img_array, (img_size, img_size))\n                X.append(new_array)\n                y.append(classification)\n            except Exception as e:\n                pass","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"create_data(100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = np.array(X).reshape(-1,100,100,1)\nX = tf.keras.utils.normalize(X, axis = 1)\ny = np.array(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique, counts = np.unique(y, return_counts=True)\ndict(zip(unique, counts))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xTrain, xTest, yTrain, yTest = train_test_split(X, y, test_size = 0.1, random_state = 0)\nunique, counts = np.unique(yTrain, return_counts=True)\ndict(zip(unique, counts))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(xTrain.shape[1:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yTest = tf.keras.utils.to_categorical(yTest, 2)\nyTrain = tf.keras.utils.to_categorical(yTrain, 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, (5,5),input_shape = xTrain.shape[1:], activation = 'relu'))\n\nmodel.add(MaxPooling2D(pool_size = (5,5)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation = 'sigmoid'))\n\nmodel.add(Dense(2, activation=\"sigmoid\"))\n\nmodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n\nmodel.fit(xTrain, yTrain, batch_size = 32, epochs = 3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(xTest, yTest)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import sklearn.metrics as metrics\n\n\nprobs = model.predict_proba(xTest)\nprint(probs)\n\nfpr, tpr, threshold = metrics.roc_curve(y_true = np.ravel(yTest), y_score = np.ravel(probs), pos_label = 1)\nroc_auc = metrics.auc(fpr, tpr)\n\nplt.title('Receiver Operating Characteristic')\nplt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)\nplt.legend(loc = 'lower right')\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()","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}