{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:51:02.586061Z",
"iopub.status.busy": "2023-05-31T11:51:02.585717Z",
"iopub.status.idle": "2023-05-31T11:51:02.593440Z",
"shell.execute_reply": "2023-05-31T11:51:02.592394Z",
"shell.execute_reply.started": "2023-05-31T11:51:02.586032Z"
}
},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from tqdm import tqdm\n",
"from tensorflow.keras.preprocessing import image\n",
"from sklearn.preprocessing import label_binarize\n",
"from sklearn.model_selection import train_test_split\n",
"from keras.models import Sequential\n",
"from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, Dropout\n",
"from keras.optimizers import Adam"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.667786Z",
"iopub.status.busy": "2023-05-31T11:55:45.667374Z",
"iopub.status.idle": "2023-05-31T11:55:45.822595Z",
"shell.execute_reply": "2023-05-31T11:55:45.821479Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.667757Z"
}
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"from keras.applications.resnet_v2 import ResNet50V2\n",
"from tensorflow import keras\n",
"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
"import seaborn as sns\n",
"import matplotlib.pyplot as plt\n",
"import cv2\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.825161Z",
"iopub.status.busy": "2023-05-31T11:55:45.824796Z",
"iopub.status.idle": "2023-05-31T11:55:45.829968Z",
"shell.execute_reply": "2023-05-31T11:55:45.828863Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.825128Z"
}
},
"outputs": [],
"source": [
"import os\n",
"from tensorflow.keras.preprocessing.image import load_img"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.831997Z",
"iopub.status.busy": "2023-05-31T11:55:45.831637Z",
"iopub.status.idle": "2023-05-31T11:55:45.860368Z",
"shell.execute_reply": "2023-05-31T11:55:45.859192Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.831961Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(10222, 2)\n"
]
},
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" id | \n",
" breed | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 000bec180eb18c7604dcecc8fe0dba07 | \n",
" boston_bull | \n",
"
\n",
" \n",
" | 1 | \n",
" 001513dfcb2ffafc82cccf4d8bbaba97 | \n",
" dingo | \n",
"
\n",
" \n",
" | 2 | \n",
" 001cdf01b096e06d78e9e5112d419397 | \n",
" pekinese | \n",
"
\n",
" \n",
" | 3 | \n",
" 00214f311d5d2247d5dfe4fe24b2303d | \n",
" bluetick | \n",
"
\n",
" \n",
" | 4 | \n",
" 0021f9ceb3235effd7fcde7f7538ed62 | \n",
" golden_retriever | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" id breed\n",
"0 000bec180eb18c7604dcecc8fe0dba07 boston_bull\n",
"1 001513dfcb2ffafc82cccf4d8bbaba97 dingo\n",
"2 001cdf01b096e06d78e9e5112d419397 pekinese\n",
"3 00214f311d5d2247d5dfe4fe24b2303d bluetick\n",
"4 0021f9ceb3235effd7fcde7f7538ed62 golden_retriever"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"labels_all = pd.read_csv('data_small/New folder/labels.csv')\n",
"print(labels_all.shape)\n",
"labels_all.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.863383Z",
"iopub.status.busy": "2023-05-31T11:55:45.862940Z",
"iopub.status.idle": "2023-05-31T11:55:45.886516Z",
"shell.execute_reply": "2023-05-31T11:55:45.885072Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.863351Z"
}
},
"outputs": [],
"source": [
"breed_all = labels_all['breed']\n",
"breed_count = breed_all.value_counts()\n",
"breed_count.head()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.890591Z",
"iopub.status.busy": "2023-05-31T11:55:45.888452Z",
"iopub.status.idle": "2023-05-31T11:55:45.924310Z",
"shell.execute_reply": "2023-05-31T11:55:45.916796Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.890548Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" index | \n",
" id | \n",
" breed | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" 9 | \n",
" 0042188c895a2f14ef64a918ed9c7b64 | \n",
" scottish_deerhound | \n",
"
\n",
" \n",
" | 1 | \n",
" 12 | \n",
" 00693b8bc2470375cc744a6391d397ec | \n",
" maltese_dog | \n",
"
\n",
" \n",
" | 2 | \n",
" 79 | \n",
" 01e787576c003930f96c966f9c3e1d44 | \n",
" scottish_deerhound | \n",
"
\n",
" \n",
" | 3 | \n",
" 80 | \n",
" 01ee3c7ff9bcaba9874183135877670e | \n",
" entlebucher | \n",
"
\n",
" \n",
" | 4 | \n",
" 88 | \n",
" 021b5a49189665c0442c19b5b33e8cf1 | \n",
" entlebucher | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" index id breed\n",
"0 9 0042188c895a2f14ef64a918ed9c7b64 scottish_deerhound\n",
"1 12 00693b8bc2470375cc744a6391d397ec maltese_dog\n",
"2 79 01e787576c003930f96c966f9c3e1d44 scottish_deerhound\n",
"3 80 01ee3c7ff9bcaba9874183135877670e entlebucher\n",
"4 88 021b5a49189665c0442c19b5b33e8cf1 entlebucher"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"CLASS_NAME = ['scottish_deerhound', 'maltese_dog', 'afghan_hound', 'entlebucher', 'bernese_mountain_dog']\n",
"labels = labels_all[(labels_all['breed'].isin(CLASS_NAME))]\n",
"labels = labels.reset_index()\n",
"labels.head()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:45.934744Z",
"iopub.status.busy": "2023-05-31T11:55:45.931530Z",
"iopub.status.idle": "2023-05-31T11:55:45.955887Z",
"shell.execute_reply": "2023-05-31T11:55:45.954669Z",
"shell.execute_reply.started": "2023-05-31T11:55:45.934705Z"
}
},
"outputs": [],
"source": [
"train_path = 'data_small/New folder/train'\n",
"\n",
"\n",
"#reading dataset labels\n",
"train_labels = pd.read_csv('data_small/New folder/labels.csv')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:46.081478Z",
"iopub.status.busy": "2023-05-31T11:55:46.080604Z",
"iopub.status.idle": "2023-05-31T11:55:46.105439Z",
"shell.execute_reply": "2023-05-31T11:55:46.103383Z",
"shell.execute_reply.started": "2023-05-31T11:55:46.081439Z"
}
},
"outputs": [],
"source": [
"train_labels.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T12:01:44.672309Z",
"iopub.status.busy": "2023-05-31T12:01:44.671926Z",
"iopub.status.idle": "2023-05-31T12:01:44.723863Z",
"shell.execute_reply": "2023-05-31T12:01:44.722593Z",
"shell.execute_reply.started": "2023-05-31T12:01:44.672280Z"
}
},
"outputs": [],
"source": [
"# Create X_data as a pandas dataframe\n",
"X_data = pd.DataFrame(columns=['image'])\n",
"\n",
"# Loop over the images and load them into X_data\n",
"for i, file_path in enumerate(train_labels):\n",
" img = cv2.imread(file_path)\n",
" print(i, file_path, img)\n",
" x = np.expand_dims(img,axis=0)\n",
" print(i, x)\n",
" X_data.loc[i] = x[i] / 255.0\n",
"\n",
"# Create train_labels as a pandas dataframe\n",
"train_labels = pd.read_csv('/kaggle/input/dog-breeding/New folder/train')\n",
"\n",
"# Merge X_data and train_labels on the 'id' column\n",
"train_data = pd.merge(X_data, train_labels, on='id')\n",
"\n",
"# Print train image and one hot encode shape & size\n",
"print('\\nTrain Images shape:', X_data.shape, ' size: {:,}'.format(X_data.size))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:55:48.195541Z",
"iopub.status.busy": "2023-05-31T11:55:48.194955Z",
"iopub.status.idle": "2023-05-31T11:55:48.400186Z",
"shell.execute_reply": "2023-05-31T11:55:48.399006Z",
"shell.execute_reply.started": "2023-05-31T11:55:48.195507Z"
}
},
"outputs": [],
"source": [
"x = train_labels.breed.unique()\n",
"include = ['beagle', 'chihuahua', 'doberman','french_bulldog', 'golden_retriever', 'malamute', 'pug', 'saint_bernard', 'scottish_deerhound','tibetan_mastiff']\n",
"for i in x :\n",
" if i not in include:\n",
" train_labels = train_labels.drop(train_labels[ train_labels['breed'] == i ].index)\n",
"print(train_labels.shape)\n",
"train_labels.head()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"execution": {
"iopub.execute_input": "2023-05-31T11:51:03.032746Z",
"iopub.status.busy": "2023-05-31T11:51:03.029528Z",
"iopub.status.idle": "2023-05-31T11:51:04.762119Z",
"shell.execute_reply": "2023-05-31T11:51:04.759538Z",
"shell.execute_reply.started": "2023-05-31T11:51:03.032713Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 588/588 [00:00<00:00, 630.73it/s]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Train Images shape: (3, 1, 224, 224, 3) size: 451,584\n",
"One-hot encoded output shape: (3, 5) size: 15\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\n"
]
}
],
"source": [
"# fix --- different data structure to store imgs and ids\n",
"# X_data = np.zeros((len(labels), 224, 224, 3), dtype='float32')\n",
"X_data = []\n",
"ids = []\n",
"valid_indices = []\n",
"\n",
"# One hot encoding\n",
"Y_data = label_binarize(labels['breed'], classes = CLASS_NAME)\n",
"\n",
"# Reading and converting image to numpy array and normalizing dataset\n",
"for i in tqdm(range(len(labels))):\n",
" try: # for fast reproducing and fixing purposes (because of sampled data)\n",
" img = image.load_img(f'data_small/New folder/train/{labels[\"id\"][i]}.jpg', target_size=(224, 224))\n",
" except FileNotFoundError:\n",
" continue\n",
" img = image.img_to_array(img)\n",
" \n",
" \n",
" x = np.expand_dims(img.copy(), axis=0)\n",
" \n",
" # fix --- different data structure to store imgs and ids\n",
" X_data.append(x / 255.0)\n",
" ids.append(labels.iloc[i]['id'])\n",
" valid_indices.append(i)\n",
"\n",
"X_data = np.array(X_data)\n",
"Y_data = Y_data[valid_indices]\n",
"\n",
"# Printing train image and one hot encode shape & size\n",
"print('\\nTrain Images shape: ',X_data.shape,' size: {:,}'.format(X_data.size))\n",
"print('One-hot encoded output shape: ',Y_data.shape,' size: {:,}'.format(Y_data.size))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.763647Z",
"iopub.status.idle": "2023-05-31T11:51:04.764242Z",
"shell.execute_reply": "2023-05-31T11:51:04.763903Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.763875Z"
}
},
"outputs": [],
"source": [
"plt.figure(figsize=(18,4))\n",
"cp = sns.countplot(x = 'breed', data = train_labels)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.766193Z",
"iopub.status.idle": "2023-05-31T11:51:04.766701Z",
"shell.execute_reply": "2023-05-31T11:51:04.766459Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.766438Z"
}
},
"outputs": [],
"source": [
"invalid_files = []\n",
"for filename in filenames:\n",
" try:\n",
" load_img(os.path.join(data_dir, filename))\n",
" except:\n",
" invalid_files.append(filename)\n",
"\n",
"print(f\"Number of invalid files: {len(invalid_files)}\")\n",
"print(\"Invalid files: \", invalid_files)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.769183Z",
"iopub.status.idle": "2023-05-31T11:51:04.769966Z",
"shell.execute_reply": "2023-05-31T11:51:04.769748Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.769725Z"
}
},
"outputs": [],
"source": [
"train_datagen = ImageDataGenerator(\n",
" rescale = 1./255, \n",
" validation_split = 0.2,\n",
" shear_range = 0.2, \n",
" zoom_range = 0.2, horizontal_flip = True, \n",
" width_shift_range = 0.2,\n",
" height_shift_range = 0.2,\n",
" rotation_range = 20,\n",
" brightness_range=[0.2,1.0])\n",
"\n",
"train_set = train_datagen.flow_from_dataframe(dataframe = train_labels,\n",
" directory = train_path,\n",
" x_col = \"id\",\n",
" y_col = \"breed\",\n",
" batch_size = 16,\n",
" subset=\"training\",\n",
" class_mode = \"categorical\",\n",
" target_size = (224,224),\n",
" seed = 42,\n",
" shuffle = True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.771346Z",
"iopub.status.idle": "2023-05-31T11:51:04.772100Z",
"shell.execute_reply": "2023-05-31T11:51:04.771888Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.771865Z"
}
},
"outputs": [],
"source": [
"validate_set = train_datagen.flow_from_dataframe(dataframe = train_labels,\n",
" directory = train_path,\n",
" x_col = \"id\",\n",
" y_col = \"breed\",\n",
" batch_size = 16,\n",
" subset=\"validation\",\n",
" class_mode = \"categorical\",\n",
" target_size = (224,224),\n",
" seed = 42,\n",
" shuffle = True)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.773456Z",
"iopub.status.idle": "2023-05-31T11:51:04.774202Z",
"shell.execute_reply": "2023-05-31T11:51:04.773990Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.773966Z"
}
},
"outputs": [],
"source": [
"train_set.batch_size"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.775557Z",
"iopub.status.idle": "2023-05-31T11:51:04.776315Z",
"shell.execute_reply": "2023-05-31T11:51:04.776080Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.776058Z"
}
},
"outputs": [],
"source": [
"resnet = ResNet50V2(input_shape = [224,224,3], weights = 'imagenet', include_top = False)\n",
"\n",
"for layer in resnet.layers:\n",
" layer.trainable = False\n",
"\n",
"x = keras.layers.Flatten()(resnet.output)\n",
"\n",
"x = keras.layers.Dropout(0.4)(x)\n",
"\n",
"pred = keras.layers.Dense(10, activation='softmax')(x)\n",
"\n",
"model = tf.keras.models.Model(inputs=resnet.input, outputs=pred)\n",
"\n",
"opt = tf.keras.optimizers.Adam(learning_rate = 1e-5)\n",
"model.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])\n",
"\n",
"train_step = train_set.n//train_set.batch_size\n",
"validate_step = validate_set.n//validate_set.batch_size\n",
"\n",
"resnet50 = model.fit(train_set,validation_data = validate_set,epochs = 30,steps_per_epoch = train_step, validation_steps = validate_step)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.777684Z",
"iopub.status.idle": "2023-05-31T11:51:04.778473Z",
"shell.execute_reply": "2023-05-31T11:51:04.778252Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.778229Z"
}
},
"outputs": [],
"source": [
"X_train_and_val, X_test, Y_train_and_val, Y_test = train_test_split(X_data, Y_data, test_size = 0.1)\n",
"\n",
"X_train, X_val, Y_train, Y_val = train_test_split(X_train_and_val, Y_train_and_val, test_size = 0.2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.779816Z",
"iopub.status.idle": "2023-05-31T11:51:04.780606Z",
"shell.execute_reply": "2023-05-31T11:51:04.780386Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.780355Z"
}
},
"outputs": [],
"source": [
"epochs = 50\n",
"batch_size = 62\n",
"\n",
"history = model.fit(X_train, Y_train, batch_size = batch_size, epochs = epochs, validation_data = (X_val, Y_val))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.781954Z",
"iopub.status.idle": "2023-05-31T11:51:04.782718Z",
"shell.execute_reply": "2023-05-31T11:51:04.782506Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.782484Z"
}
},
"outputs": [],
"source": [
"Y_pred = model.predict(X_test)\n",
"score = model.evaluate(X_test, Y_test)\n",
"print('Accuracy over the test set: \\n ', round((score[1]*100), 2), '%')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.784137Z",
"iopub.status.idle": "2023-05-31T11:51:04.784918Z",
"shell.execute_reply": "2023-05-31T11:51:04.784705Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.784681Z"
}
},
"outputs": [],
"source": [
"plt.figure(figsize=(12, 5))\n",
"plt.plot(history.history['accuracy'])\n",
"plt.plot(history.history['val_accuracy'])\n",
"plt.title('Model Accuracy')\n",
"plt.ylabel('Accuracy')\n",
"plt.xlabel('Epochs')\n",
"plt.legend(['train', 'val'])\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.status.busy": "2023-05-31T11:51:04.786277Z",
"iopub.status.idle": "2023-05-31T11:51:04.787025Z",
"shell.execute_reply": "2023-05-31T11:51:04.786809Z",
"shell.execute_reply.started": "2023-05-31T11:51:04.786787Z"
}
},
"outputs": [],
"source": [
"plt.imshow(X_test[1,:,:,:])\n",
"plt.show()\n",
"\n",
"# Finding max value from predition list and comaparing original value vs predicted\n",
"print(\"Originally : \",labels['breed'][np.argmax(Y_test[1])])\n",
"print(\"Predicted : \",labels['breed'][np.argmax(Y_pred[1])])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}