{"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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"df_train = pd.read_csv('../input/labels.csv')\ndf_test = pd.read_csv('../input/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.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":"train_files = glob('../input/train/*.jpg')\ntest_files = glob('../input/test/*.jpg')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(plt.imread(train_files[99]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_trial = plt.imread(train_files[99])\ndef crop_center(img,cropx,cropy):\n    y,x = image_trial.shape[0:2]\n    startx = x//2-(cropx//2)\n    starty = y//2-(cropy//2)    \n    plt.imshow(image_trial[starty:starty+cropy,startx:startx+cropx])\n    \ncrop_center(image_trial,150,150)\n\ndef crop_left(img,cropx,cropy):\n    y,x = image_trial.shape[0:2]\n    startx = x//2-(cropx//2)\n    starty = y//2-(cropy//2)    \n    plt.imshow(image_trial[0:cropy,0:cropx])\n    \ncrop_left(image_trial,150,150)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"targets_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":"one_hot.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"im_size = 300","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_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":"i = 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":"print(x_train_raw.shape)\nprint(x_val_raw.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class DataGenerator(keras.utils.Sequence):\n    'Generates data for Keras'\n    def __init__(self, data, labels, im_size, batch_size, shuffle=True, data_augment = False, test = False):\n        'Initialization'\n        self.batch_size = batch_size\n        self.list_IDs = np.arange(0,data.shape[0])\n        self.shuffle = shuffle\n        if self.shuffle == True:\n            np.random.shuffle(self.list_IDs)        \n        self.data = data\n        self.data_augment = data_augment\n        self.test = test\n        if self.test == False:\n            self.labels = labels\n        self.on_epoch_end()\n        \n    def __len__(self):\n        'Denotes the number of batches per epoch'\n        return int(np.floor(len(self.list_IDs) / self.batch_size))\n\n    def __getitem__(self, index):\n        'Generate one batch of data'\n        # Generate indexes of the batch\n        indexes = self.list_IDs[index*self.batch_size:(index+1)*self.batch_size]\n\n        # Generate data\n        if self.test == False:\n            X, y = self.__data_generation(indexes)\n            return preprocess_input(X), y\n        else:\n            X = self.__data_generation(indexes)\n            return preprocess_input(X)\n        \n    def on_epoch_end(self):\n        'Updates indexes after each epoch'\n        if self.shuffle == True:\n            np.random.shuffle(self.list_IDs)\n            \n    def __data_generation(self, list_IDs_temp):\n        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)\n        # Initialization\n        X = np.zeros((list_IDs_temp.shape[0],im_size,im_size,3), dtype=np.float32)\n        if self.test == False:\n            y = np.zeros((list_IDs_temp.shape[0],self.labels.shape[1]), dtype=np.uint8)\n\n        # Generate data\n        for i, ID in enumerate(list_IDs_temp):\n            \n            if self.data_augment == True:\n                if random.randint(1,101) < 20:\n                    crop_center(x_train_raw[i],150,150)\n                    x_train_raw.append(image)\n                    y_train.append(label)\n                    \n                    if random.randint(1,101) < 50: \n                        flip_horizontal = True\n                    else:\n                        flip_horizontal = False\n                    if random.randint(1,101) < 50: \n                        flip_vertical = True\n                    else:\n                        flip_vertical = False\n                    tx = im_size*random.randint(1,2)/100.0\n                    ty = im_size*random.randint(1,2)/100.0\n                    shear = random.randint(1,10)/100.0\n                    zx = random.randint(80,120)/100.0\n                    zy = random.randint(80,120)/100.0\n                    brightness = random.randint(1,2)/100.0\n                    channel_shift_intensity = random.randint(1,10)/100.0\n                    \n                \n                \n                    X[i,] = self.data[ID,]\n            else:\n                # Store sample\n                X[i,] = self.data[ID,]\n\n            # Store class\n            if self.test == False:\n                y[i,] = self.labels[ID,]\n\n        if self.test == False:\n            return X, y\n        else:\n            return X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32\n\n\n# Parameters\nparams_trn = {\n          'im_size': im_size,\n          'batch_size': batch_size,\n          'shuffle': True,\n          'data_augment' : True,\n          'test' : False\n         }\nparams_val = {\n          'im_size': im_size,\n          'batch_size': batch_size,\n          'shuffle': True,\n          'data_augment' : False,\n          'test' : False\n         }\n\n# Generators\ntraining_generator = DataGenerator(x_train_raw, y_train, **params_trn)\nvalidation_generator = DataGenerator(x_val_raw, y_val, **params_val)","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}