{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nfrom PIL import Image\nfrom IPython.display import HTML\nimport matplotlib.pyplot as plt\n\nfrom keras.layers import Dense,Dropout,Input,MaxPooling2D,ZeroPadding2D,Conv2D,Flatten\nfrom keras.models import Sequential\nfrom keras.losses import categorical_crossentropy\nfrom keras.optimizers import Adam,SGD\nfrom keras.preprocessing.image import img_to_array,load_img,ImageDataGenerator\nfrom keras.utils import to_categorical","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\nlabels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_breeds = labels['breed'].unique()\nlen(unique_breeds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# path of the dogs images\nimg_file='/kaggle/input/dog-breed-identification/train/'\nlabels=labels.assign(img_path=lambda x: img_file + x['id'] +'.jpg')\nlabels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a=labels['breed'].value_counts()\npd.DataFrame(a).head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"so most popular breed in dataset is scottish deerhound with 126 images."},{"metadata":{"trusted":true},"cell_type":"code","source":"ax=pd.value_counts(labels['breed'],ascending=True).plot(kind='barh',fontsize=\"40\",title=\"Class Distribution\",figsize=(50,100))\nax.set(xlabel=\"Images per class\", ylabel=\"Classes\")\nax.xaxis.label.set_size(40)\nax.yaxis.label.set_size(40)\nax.title.set_size(60)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scottish_deerhound_id = labels.loc[labels.breed == \"scottish_deerhound\"].iloc[1,0]\nImage.open('/kaggle/input/dog-breed-identification/train/'+scottish_deerhound_id+\".jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"top_20=list(labels['breed'].value_counts()[:20].index)\ntop_20","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df=labels[labels['breed'].isin(top_20)]\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['img_path'].values.tolist()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For Machine Learning Operation, we are loading the images and converting it to numpy array of pixel"},{"metadata":{"trusted":true},"cell_type":"code","source":"img_pixel=np.array([img_to_array(load_img(img,target_size=(299,299))) for img in df['img_path'].values.tolist()])\nimg_pixel\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_pixel.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"label encoding of classes(dog breed)"},{"metadata":{"trusted":true},"cell_type":"code","source":"label1=pd.get_dummies(df['breed'])\nlabel1.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=img_pixel\ny=label1.values#array required in algo","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x.shape)\nprint(y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_img_gen = ImageDataGenerator(\n    rotation_range=30,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest')\n\ntest_img_gen=ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_set=train_img_gen.flow(X_train,y=y_train,batch_size=32)\ntest_set=test_img_gen.flow(X_test,y=y_test,batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=Sequential()\nmodel.add(Conv2D(32,kernel_size=(3,3),input_shape=(299,299,3),activation='relu',padding='same'))\n#model.add(Conv2D(32,kernel_size=(3,3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(64,activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(20,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss=categorical_crossentropy,optimizer='adam',metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size=32\nmodel.fit_generator(\n    train_set,\n    epochs=2, steps_per_epoch=len(X_train) / batch_size,\n    validation_data=(np.array(X_train), np.array(y_train)), validation_steps=len(X_test) / batch_size)","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}