{"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', batch_size=32,target_size=(224,224))\n\nvaldata = ImageDataGenerator()\nval_data = valdata.flow_from_dataframe(valid_df, TRAIN_DIR,  x_col='id',y_col='label', batch_size=32,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()\nmodel.add(Conv2D(input_shape=(224,224,3),filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=128, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=256, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(Conv2D(filters=512, kernel_size=(3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(units=4096,activation=\"relu\"))\nmodel.add(Dense(units=4096,activation=\"relu\"))\nmodel.add(Dense(units=2, activation=\"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":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}