{"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 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Extracting from the Zip file"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\") as train:\n    train.extractall(\".\")\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\") as test:\n    test.extractall(\".\")    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.config.experimental.list_physical_devices(\"GPU\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir('/kaggle/working/train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label = []\nfor file in filenames:\n    label.append(file.split(\".\")[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoder = LabelEncoder()\nencoder.fit(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = encoder.transform(label)\ny = y.astype(str)\n# For train data generate y label must be string, list,tuple not an int","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y[:4]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoder.classes_","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Display the Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"import random","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = random.choice(filenames)\nimage","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import load_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f  = load_img(\"/kaggle/working/train/\"+image)\nplt.imshow(f)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file = {'filename':filenames,'label':y}\ndf = pd.DataFrame(file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head(2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Genetaring train and Validation sets"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train,y_train = train_test_split(df,test_size = 0.3,random_state = 21)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train.head(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.reset_index(drop= True)\ny_train = y_train.reset_index(drop= True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = 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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen = train_data.flow_from_dataframe(X_train,'/kaggle/working/train/',\n                                           x_col='filename',y_col='label',target_size=(128,128),\n                                          class_mode='categorical',batch_size=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#valid_data = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_gen = train_data.flow_from_dataframe(y_train,'/kaggle/working/train/',\n                                           x_col='filename',y_col='label',target_size=(128,128),\n                                          class_mode='categorical',batch_size=10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Define the MOdel-----CNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import Sequential,layers,optimizers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(layers.Conv2D(filters= 64,kernel_size = 3,activation='relu',input_shape= (128,128,3),padding = 'same'))\nmodel.add(layers.MaxPool2D(pool_size = (2,2)))\nmodel.add(layers.Conv2D(filters= 32,kernel_size = 3,activation='relu',padding = 'same',strides = (2,2)))\nmodel.add(layers.MaxPool2D(pool_size = (2,2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64,activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(32,activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(2,activation= 'sigmoid'))       ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=optimizers.Adam(learning_rate=0.001),loss = 'categorical_crossentropy',metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_gen,validation_data=valid_gen,epochs=10,batch_size = 10,verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filenames = os.listdir(\"/kaggle/working/test1\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame({\n    'filename': test_filenames,\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data_gen = test_data.flow_from_dataframe(\n    test_df, \n    \"/kaggle/working/test1\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=(128,128),\n    batch_size=15,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(test_data_gen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = np.argmax(predictions,axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from collections import Counter","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Counter(results)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('/kaggle/input/dogs-vs-cats/sampleSubmission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label = []\nfor i in results:\n    if i ==0:\n        label.append('cat')\n    else:\n        label.append('dog')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['label']= label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv(\"submission.csv\",index = False)","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}