{"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 5GB 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":{},"cell_type":"markdown","source":"Preparing Data:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\n\n\nzip_files = ['test1', 'train']\n# Will unzip the files so that you can see them..\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nTRAIN_DIR = \"../working/train\"\nTEST_DIR = \"../working/test1\"\n\nTRAIN_SIZE = len([name for name in os.listdir(TRAIN_DIR)])\nTEST_SIZE = len([name for name in os.listdir(TEST_DIR)])\nprint(\"Number of training images:\", TRAIN_SIZE)\nprint(\"Number of test images:\", TEST_SIZE)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# creating df with train labels\ntrain_filenames = os.listdir(TRAIN_DIR)\ntrain_labels = []\nfor filename in train_filenames:\n    label = filename.split('.')[0]\n    train_labels.append(label)\n\ntrain_df = pd.DataFrame({\n    'id': train_filenames,\n    'label': train_labels\n})\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['label'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Train and test Split:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# splitting to train & valid\nfrom sklearn.model_selection import train_test_split\ntrain_df, valid_df = train_test_split(train_df, test_size=0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape,valid_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nimport matplotlib.pyplot as plt\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, MaxPool2D,GlobalMaxPooling2D, Dropout\nfrom keras.optimizers import Adam,SGD,Adagrad,Adadelta,RMSprop\nfrom keras.utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\ntrdata = ImageDataGenerator()\ntraindata = trdata.flow_from_dataframe(train_df,TRAIN_DIR, x_col='id',y_col='label',target_size=(224,224))\n\nvaldata = ImageDataGenerator()\nval_data = valdata.flow_from_dataframe(valid_df, TRAIN_DIR,  x_col='id',y_col='label',target_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n# 1st Convolutional Layer\nmodel.add(Conv2D(filters=96, input_shape=(224,224,3), kernel_size=(11,11), strides=(4,4), padding=\"valid\", activation = \"relu\"))\n\n# Max Pooling\nmodel.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding=\"valid\"))\n\n# 2nd Convolutional Layer\nmodel.add(Conv2D(filters=256, kernel_size=(5,5), strides=(1,1), padding=\"same\", activation = \"relu\"))\n\n# Max Pooling\nmodel.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding=\"valid\"))\n\n# 3rd Convolutional Layer\nmodel.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding=\"same\", activation = \"relu\"))\n\n# 4th Convolutional Layer\nmodel.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding=\"same\", activation = \"relu\"))\n\n# 5th Convolutional Layer\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding=\"same\", activation = \"relu\"))\n\n# Max Pooling\nmodel.add(MaxPool2D(pool_size=(3,3), strides=(2,2), padding=\"valid\"))\n\n# Passing it to a Fully Connected layer\nmodel.add(Flatten())\n# 1st Fully Connected Layer\nmodel.add(Dense(units = 9216, activation = \"relu\"))\n\n# 2nd Fully Connected Layer\nmodel.add(Dense(units = 4096, activation = \"relu\"))\n\n# 3rd Fully Connected Layer\nmodel.add(Dense(4096, activation = \"relu\"))\n\n# Output Layer\nmodel.add(Dense(2, activation = \"softmax\")) #As we have two classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.optimizers import Adam\nopt = Adam(lr=0.001)\nmodel.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, EarlyStopping\ncheckpoint = ModelCheckpoint(\"alexnet_replica.h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)\nearly = EarlyStopping(monitor='val_acc', min_delta=0, patience=20, verbose=1, mode='auto')\nhistory = model.fit_generator(steps_per_epoch=10,generator=traindata, validation_data= val_data, validation_steps=10,epochs=10,callbacks=[checkpoint,early])","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}