{"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 \nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport keras\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten,  Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras import backend as K\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.preprocessing.image import load_img\n#from keras.applications.vgg16 import preprocess_input\nfrom keras.applications.resnet50 import preprocess_input\nfrom keras.preprocessing.image import img_to_array\nimport os\nfrom tqdm import tqdm\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nimport cv2\nimport sys\nimport bcolz\nimport random\n\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 the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\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":"# Reading the csv data - each ID/picture in train corresponds to ab image\ndf_train = pd.read_csv('../input/labels.csv')\n\n# Reading the sample of submission file - for each ID/picture, we have to predict the each of the dog probability\ndf_test = pd.read_csv('../input/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Printing top 10 rows\ndf_train.head(10) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom mpl_toolkits.axes_grid1 import ImageGrid","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Importing all the pictures for the train and test\ntrain_files = glob('../input/train/*.jpg')\ntest_files = glob('../input/test/*.jpg')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Printing the 100th image from train\nplt.imshow(plt.imread(train_files[100]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Creating dummy flags for the train data and storing them in array\ntargets_series = pd.Series(df_train['breed'])\none_hot = pd.get_dummies(targets_series, sparse = True)\none_hot_labels = np.asarray(one_hot)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Sample\nprint(one_hot_labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Defining the image size for storage\nim_size = 300","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Inititalizing a bcolz array of the required size i.e. no. of pics x image size x image size x 3(for RGB)\ny_train = []\ny_val = []\nx_train_raw = bcolz.zeros((0,im_size,im_size,3),np.float32)\nx_val_raw = bcolz.zeros((0,im_size,im_size,3),np.float32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Running a loop to store each of the pictures in bcolz and splitting the list of image in 80-20\ni = 0 \nfor f, breed in tqdm(df_train.values):\n    # load an image from file\n    image = load_img('../input/train/{}.jpg'.format(f), target_size=(im_size, im_size))\n    image = img_to_array(image)\n    # prepare the image for the VGG model\n    #image = preprocess_input(image)\n    label = one_hot_labels[i]\n    if random.randint(1,101) < 80: \n        x_train_raw.append(image)\n        y_train.append(label)\n    else:\n        x_val_raw.append(image)\n        y_val.append(label)\n    i += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Creating a numpy array for the flags\ny_train_raw = np.array(y_train, np.uint8)\ny_val_raw = np.array(y_val, np.uint8)\ndel(y_train,y_val)\n\n# Garbage collection feature of python\nimport gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Checking the dimension of image arrays(in form of RGB) and the label array (one hot encoded)\nprint(x_train_raw.shape)\nprint(y_train_raw.shape)\nprint(x_val_raw.shape)\nprint(y_val_raw.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Defining a function for printing images in defined format\ndef plotImages( images_arr, n_images = 2):\n    fig, axes = plt.subplots(n_images, n_images, figsize=(12,12))\n    axes = axes.flatten()\n    for img, ax in zip( images_arr, axes):\n        ax.imshow(img)\n        ax.set_xticks(())\n        ax.set_yticks(())\n    plt.tight_layout()\n\n# Running the function to print the first 16 pictures\nplotImages(x_train_raw[0:4,]/255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotImages(x_train_raw[10:11,]/255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Shape of a picture : image_size x image_size x 3(RGB)\nnp.shape(x_train_raw[0,])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotImages(x_train_raw[10:11,]/255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator()\ntemp = np.zeros((16,im_size,im_size,3),dtype=np.float32)\nimage_to_test = 10\nfor i in range(16):\n    if random.randint(1,101) < 50: \n        flip_horizontal = False\n    else:\n        flip_horizontal = False\n    if random.randint(1,101) < 50: \n        flip_vertical = False\n    else:\n        flip_vertical = False\n    \n    if random.randint(1,101) < 50:\n        tx = im_size*random.randint(1,15)/100.0\n    else:\n        tx = im_size*random.randint(-15,-1)/100.0\n        \n    if random.randint(1,101) < 50:\n        ty = im_size*random.randint(1,15)/100.0\n    else:\n        ty = im_size*random.randint(-15,-1)/100.0\n    \n\n    zx = 1\n    zy = 1\n    brightness = random.randint(1,2)/100.0  # Range from 0.01 to 0.02\n    channel_shift_intensity = random.randint(1,10)/100.0  # Range from 0.01 to 0.1\n    \n    temp[i] = datagen.apply_transform(x_train_raw[image_to_test],{\n        'tx':tx,\n        'ty':ty,\n        'shear':shear,\n        'zx':zx,\n        'zy':zy,\n        'flip_horizontal':flip_horizontal,\n        'flip_vertical':flip_vertical,\n        #'brightness':brightness,\n        #'channel_shift_intensity':channel_shift_intensity\n        })\n    plotImages(temp[0:16,]/255.0) \n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}