{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-06-23T06:58:59.856648Z","iopub.execute_input":"2021-06-23T06:58:59.857388Z","iopub.status.idle":"2021-06-23T06:58:59.865584Z","shell.execute_reply.started":"2021-06-23T06:58:59.85727Z","shell.execute_reply":"2021-06-23T06:58:59.864435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import libraries\n\nimport numpy as np\nimport pandas as pd\nfrom keras.preprocessing.image import ImageDataGenerator,load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:04:52.663277Z","iopub.execute_input":"2021-06-23T07:04:52.663628Z","iopub.status.idle":"2021-06-23T07:04:52.670416Z","shell.execute_reply.started":"2021-06-23T07:04:52.663597Z","shell.execute_reply":"2021-06-23T07:04:52.669007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#define image properties:\n\nimage_width=128\nimge_height =128\nimage_size=(image_width,imge_height)\nimage_channels=3","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:06:49.549043Z","iopub.execute_input":"2021-06-23T07:06:49.549474Z","iopub.status.idle":"2021-06-23T07:06:49.555625Z","shell.execute_reply.started":"2021-06-23T07:06:49.549441Z","shell.execute_reply":"2021-06-23T07:06:49.553873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#prepare dataset for training model:\n\n\nfilenames =(\"../input/dogs-vs-cats/train.zip\")\n\ncategories=[]\nfor f_name in filenames:\n    category = f_name.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\ndf = pd.DataFrame({\n    'filename':filenames,\n    'category':categories})\n\n","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:12:30.121075Z","iopub.execute_input":"2021-06-23T07:12:30.121523Z","iopub.status.idle":"2021-06-23T07:12:30.132119Z","shell.execute_reply.started":"2021-06-23T07:12:30.121485Z","shell.execute_reply":"2021-06-23T07:12:30.130636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#creating the neural net model:\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Dropout,Flatten,Dense,\\\nActivation,BatchNormalization\n\nmodel=Sequential()\n\nmodel.add(Conv2D(32,(3,3),activation='relu',input_shape=(image_width,imge_height,image_channels)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2,activation='softmax'))\n\nmodel.compile(loss=\"categorical_crossentropy\",\n             optimizer = 'rmsprop',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:31:32.195573Z","iopub.execute_input":"2021-06-23T07:31:32.196002Z","iopub.status.idle":"2021-06-23T07:31:32.524251Z","shell.execute_reply.started":"2021-06-23T07:31:32.19596Z","shell.execute_reply":"2021-06-23T07:31:32.523142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#analyzing model:\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:32:18.050273Z","iopub.execute_input":"2021-06-23T07:32:18.05071Z","iopub.status.idle":"2021-06-23T07:32:18.060978Z","shell.execute_reply.started":"2021-06-23T07:32:18.050672Z","shell.execute_reply":"2021-06-23T07:32:18.059587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#define callback and learning rate:\n\nfrom keras.callbacks import EarlyStopping,ReduceLROnPlateau\nearlystop = EarlyStopping(patience=10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience =2,verbose=1,\n                                           factor=0.5,min_lr=0.00001)\n\ncallbacks=[earlystop,learning_rate_reduction]","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:37:55.628746Z","iopub.execute_input":"2021-06-23T07:37:55.629149Z","iopub.status.idle":"2021-06-23T07:37:55.635378Z","shell.execute_reply.started":"2021-06-23T07:37:55.629116Z","shell.execute_reply":"2021-06-23T07:37:55.633967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Manage data:\n\ndf['category'] = df['category'].replace({0:'cat',1:'dog'})\ntrain_df,validate_df = train_test_split(df,test_size=0.20,random_state=42)\n\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df =validate_df.reset_index(drop=True)\n\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15","metadata":{"execution":{"iopub.status.busy":"2021-06-23T07:50:44.694429Z","iopub.execute_input":"2021-06-23T07:50:44.69488Z","iopub.status.idle":"2021-06-23T07:50:44.719749Z","shell.execute_reply.started":"2021-06-23T07:50:44.694828Z","shell.execute_reply":"2021-06-23T07:50:44.718127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rotation_range=15,\n                                rescale=1./255,\n                                shear_range=0.1,\n                                zoom_range=0.2,\n                                horizontal_flip=True,\n                                width_shift_range=0.1,\n                                height_shift_range=0.1\n                                )\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df,\n                                                 \"../input/dogs-vs-cats/train.zip\",x_col='filename',y_col='category',\n                                                 target_size=image_size,\n                                                 class_mode='categorical',\n                                                 batch_size=batch_size)\n\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"../input/dogs-vs-cats/train.zip\", \n    x_col='filename',\n    y_col='category',\n    target_size=image_size,\n    class_mode='categorical',\n    batch_size=batch_size\n)\n\ntest_datagen = ImageDataGenerator(rotation_range=15,\n                                rescale=1./255,\n                                shear_range=0.1,\n                                zoom_range=0.2,\n                                horizontal_flip=True,\n                                width_shift_range=0.1,\n                                height_shift_range=0.1)\n\nTEST_BATCH = 20\ntest_generator = train_datagen.flow_from_dataframe(train_df,\n                                                 \"../input/dogs-vs-cats/test1.zip\",x_col='filename',y_col='category',\n                                                   target_size=image_size,\n                                                   class_mode=None,\n                                                   batch_size=TEST_BATCH)\n\n\n\n","metadata":{"execution":{"iopub.status.busy":"2021-06-23T08:26:53.417472Z","iopub.execute_input":"2021-06-23T08:26:53.417912Z","iopub.status.idle":"2021-06-23T08:26:53.438522Z","shell.execute_reply.started":"2021-06-23T08:26:53.417878Z","shell.execute_reply":"2021-06-23T08:26:53.437494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#model Training\nepochs=10\nhistory = model.fit_generator(\n    train_generator, \n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","metadata":{"execution":{"iopub.status.busy":"2021-06-23T08:27:00.423998Z","iopub.execute_input":"2021-06-23T08:27:00.424362Z","iopub.status.idle":"2021-06-23T08:27:00.463118Z","shell.execute_reply.started":"2021-06-23T08:27:00.424327Z","shell.execute_reply":"2021-06-23T08:27:00.460358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}