{"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 matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",'r') as zip_ref:\n    zip_ref.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",'r') as zip_ref:\n    zip_ref.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_path='./train'\ntest_path='./test1'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames=os.listdir('./train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories=[]\nfor i in filenames:\n    category=i.split('.')[0]\n    if category=='dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.DataFrame({'file':filenames,'category':categories})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=train['category'].map({1:'dog',0:'cat'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"k=0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(4):\n    plt.figure(figsize=(4,4))\n    plt.imshow(image.load_img(os.path.join(train_path,filenames[k])))\n    plt.title(labels[k])\n    k+=1","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":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train,val= train_test_split(train, train_size=0.75)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(rescale=1/255,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.5,rotation_range=40,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')\ntest_datagen=ImageDataGenerator(rescale=1/255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['category']=train['category'].map({1:'dog',0:'cat'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val['category']=val['category'].map({1:'dog',0:'cat'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_dataframe(train, directory=train_path, x_col='file', y_col='category', target_size=(150,150), class_mode='binary', batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_generator=test_datagen.flow_from_dataframe(val, directory=train_path,x_col='file', y_col='category', target_size=(150,150), class_mode='binary', batch_size=20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import ResNet50, MobileNet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mnet=MobileNet(input_shape=(150,150,3), include_top=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mnet.trainable=False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mnet.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=tf.keras.models.Sequential([mnet,\n                                  tf.keras.layers.Flatten(),\n                                  tf.keras.layers.Dense(32, activation='relu'),\n                                  tf.keras.layers.Dense(1, activation='sigmoid')\n                                 ])","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='adam', metrics=['accuracy'], loss='binary_crossentropy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator[0][0][0].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train_generator,epochs=5,validation_data=val_generator,validation_steps=250)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_names=os.listdir('./test1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test=pd.DataFrame({'file':test_names})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator=test_datagen.flow_from_dataframe(test, directory=test_path,x_col='file', y_col=None, target_size=(150,150), class_mode=None, batch_size=20, shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict=model.predict(test_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(predict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"k=0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i,j in zip(test_names[k:k+6],range(6)):\n    plt.subplot(2,3,j+1)\n    plt.imshow(image.load_img(os.path.join(test_path,i)))\n    plt.title(predict[k+j])\nk+=4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred=[]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in predict:\n    if i>0.5:\n        pred.append(1)\n    else:\n        pred.append(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred=np.asarray(pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred=pred.reshape(-1,)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission=pd.DataFrame()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ids=[]\nfor i in test_names:\n    ids.append(i.split('.')[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['id']=ids","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['labels']=pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"k=0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i,j,m in zip(submission['id'][k:k+6],submission['labels'][k:k+6], range(6)):\n    plt.subplot(2,3,m+1)\n    plt.imshow(image.load_img(os.path.join(test_path,(i+'.jpg'))))\n    plt.title(j)\n    k+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","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}