{"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":"import os\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom glob import glob","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-01-10T20:15:09.839889Z","iopub.execute_input":"2023-01-10T20:15:09.840340Z","iopub.status.idle":"2023-01-10T20:15:09.847101Z","shell.execute_reply.started":"2023-01-10T20:15:09.840292Z","shell.execute_reply":"2023-01-10T20:15:09.845694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the labels csv\ndf = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:15:10.134118Z","iopub.execute_input":"2023-01-10T20:15:10.135232Z","iopub.status.idle":"2023-01-10T20:15:10.153869Z","shell.execute_reply.started":"2023-01-10T20:15:10.135189Z","shell.execute_reply":"2023-01-10T20:15:10.152905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set path for the images\ntrain_path = '/kaggle/input/dog-breed-identification/train'","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:15:10.475233Z","iopub.execute_input":"2023-01-10T20:15:10.476428Z","iopub.status.idle":"2023-01-10T20:15:10.482142Z","shell.execute_reply.started":"2023-01-10T20:15:10.476373Z","shell.execute_reply":"2023-01-10T20:15:10.480692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(df['id'], df['breed'], test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:15:10.768825Z","iopub.execute_input":"2023-01-10T20:15:10.769257Z","iopub.status.idle":"2023-01-10T20:15:10.778366Z","shell.execute_reply.started":"2023-01-10T20:15:10.769221Z","shell.execute_reply":"2023-01-10T20:15:10.777169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define data generators\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n                                   rotation_range = 40,\n                                   width_shift_range = 0.2,\n                                   height_shift_range = 0.2,\n                                   shear_range = 0.2,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = True)\nval_datagen = ImageDataGenerator(rescale = 1./255)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:15:11.061096Z","iopub.execute_input":"2023-01-10T20:15:11.061505Z","iopub.status.idle":"2023-01-10T20:15:11.069434Z","shell.execute_reply.started":"2023-01-10T20:15:11.061463Z","shell.execute_reply":"2023-01-10T20:15:11.067419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Create the Generators\nX_train = X_train.to_frame()\nX_train['id'] = train_path+\"/\"+X_train['id']+'.jpg'\nX_train['y_train'] = y_train\ntrain_generator = train_datagen.flow_from_dataframe(dataframe=X_train,\n                                                 x_col='id', y_col='y_train', \n                                                 class_mode=\"categorical\",\n                                                 target_size=(224,224), \n                                                 batch_size=32,\n                                                 validate_filenames=False)\n\nval_generator = val_datagen.flow_from_dataframe(dataframe=X_train,\n                                                 x_col='id', y_col='y_train', \n                                                 class_mode=\"categorical\",\n                                                 target_size=(224,224), \n                                                 batch_size=32,\n                                                 validate_filenames=False)","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:15:11.401332Z","iopub.execute_input":"2023-01-10T20:15:11.401735Z","iopub.status.idle":"2023-01-10T20:15:11.478079Z","shell.execute_reply.started":"2023-01-10T20:15:11.401703Z","shell.execute_reply":"2023-01-10T20:15:11.476705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Build the model\nmodel = keras.Sequential()\nmodel.add(keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(224,224,3)))\nmodel.add(keras.layers.MaxPooling2D((2,2)))\nmodel.add(keras.layers.Conv2D(64, (3,3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D((2,2)))\nmodel.add(keras.layers.Conv2D(128, (3,3), activation='relu'))\nmodel.add(keras.layers.MaxPooling2D((2,2)))\nmodel.add(keras.layers.Flatten())\nmodel.add(keras.layers.Dense(128, activation='relu'))\nmodel.add(keras.layers.Dense(len(df['breed'].unique()), activation='softmax'))\n\nmodel.summary()\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit_generator(train_generator,\n                              steps_per_epoch=len(X_train)//32,\n                              epochs=50,\n                              validation_data=val_generator,\n                              validation_steps=len(X_val)//32)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:39:07.653876Z","iopub.execute_input":"2023-01-10T21:39:07.654317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_loss, val_acc = model.evaluate(val_generator)\nprint('val_loss:', val_loss)\nprint('val_acc:', val_acc)","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:35:26.210187Z","iopub.execute_input":"2023-01-10T20:35:26.210705Z","iopub.status.idle":"2023-01-10T20:37:01.122646Z","shell.execute_reply.started":"2023-01-10T20:35:26.210663Z","shell.execute_reply":"2023-01-10T20:37:01.121700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-10T20:37:06.941708Z","iopub.execute_input":"2023-01-10T20:37:06.942145Z","iopub.status.idle":"2023-01-10T20:37:07.145823Z","shell.execute_reply.started":"2023-01-10T20:37:06.942108Z","shell.execute_reply":"2023-01-10T20:37:07.144799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report, confusion_matrix\nval_generator.reset()\npredictions = model.predict(val_generator)\ny_pred = predictions.argmax(axis=-1)\ny_true = val_generator.classes\nprint('Classification Report')\ntarget_names = val_generator.class_indices.keys()\nprint(classification_report(y_true, y_pred, target_names=target_names))","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:26:09.748024Z","iopub.execute_input":"2023-01-10T21:26:09.749359Z","iopub.status.idle":"2023-01-10T21:27:42.118175Z","shell.execute_reply.started":"2023-01-10T21:26:09.749290Z","shell.execute_reply":"2023-01-10T21:27:42.116979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import the necessary libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\n\n# Choose an image to test on\nimg_path = '/kaggle/input/dog-breed-identification/train/00f34ac0a16ef43e6fd1de49a26081ce.jpg'\nimg = image.load_img(img_path, target_size=(224, 224))\nimg_tensor = image.img_to_array(img)\nimg_tensor = np.expand_dims(img_tensor, axis=0)\n\n# Scale the pixel values between 0 and 1\nimg_tensor /= 255.\n\n# Get the predicted breed\nprediction = model.predict(img_tensor)\n\n# Map the predicted class index to the breed string\nbreed_map = train_generator.class_indices\nbreed = list(breed_map.keys())[list(breed_map.values()).index(np.argmax(prediction))]\n\n# Display the image\nplt.imshow(img_tensor[0])\nplt.axis('off')\nplt.title(f'Predicted Breed: {breed}')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:00:29.796721Z","iopub.execute_input":"2023-01-10T21:00:29.797877Z","iopub.status.idle":"2023-01-10T21:00:30.387545Z","shell.execute_reply.started":"2023-01-10T21:00:29.797831Z","shell.execute_reply":"2023-01-10T21:00:30.386534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a list of image paths to test on\nimg_paths = ['/kaggle/input/dog-breed-identification/train/000bec180eb18c7604dcecc8fe0dba07.jpg',\n             '/kaggle/input/dog-breed-identification/train/001513dfcb2ffafc82cccf4d8bbaba97.jpg',\n             '/kaggle/input/dog-breed-identification/train/001cdf01b096e06d78e9e5112d419397.jpg']","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:36:24.451057Z","iopub.execute_input":"2023-01-10T21:36:24.451636Z","iopub.status.idle":"2023-01-10T21:36:24.458623Z","shell.execute_reply.started":"2023-01-10T21:36:24.451594Z","shell.execute_reply":"2023-01-10T21:36:24.456723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a list to store the images\nimages = []","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:36:37.161360Z","iopub.execute_input":"2023-01-10T21:36:37.161802Z","iopub.status.idle":"2023-01-10T21:36:37.168303Z","shell.execute_reply.started":"2023-01-10T21:36:37.161755Z","shell.execute_reply":"2023-01-10T21:36:37.166493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the images and store them in the list\nfor img_path in img_paths:\n    img = image.load_img(img_path, target_size=(224, 224))\n    img_tensor = image.img_to_array(img)\n    images.append(img_tensor)","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:36:45.611218Z","iopub.execute_input":"2023-01-10T21:36:45.611684Z","iopub.status.idle":"2023-01-10T21:36:45.640910Z","shell.execute_reply.started":"2023-01-10T21:36:45.611645Z","shell.execute_reply":"2023-01-10T21:36:45.639860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Scale the pixel values between 0 and 1\nimages = np.array(images)\nimages /= 255.","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:36:52.851786Z","iopub.execute_input":"2023-01-10T21:36:52.852340Z","iopub.status.idle":"2023-01-10T21:36:52.859433Z","shell.execute_reply.started":"2023-01-10T21:36:52.852276Z","shell.execute_reply":"2023-01-10T21:36:52.858161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a list of breeds\nbreeds = df['breed'].unique()","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:37:09.314860Z","iopub.execute_input":"2023-01-10T21:37:09.315400Z","iopub.status.idle":"2023-01-10T21:37:09.324664Z","shell.execute_reply.started":"2023-01-10T21:37:09.315357Z","shell.execute_reply":"2023-01-10T21:37:09.322517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions for each image\npredictions = model.predict(images)","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:37:15.555152Z","iopub.execute_input":"2023-01-10T21:37:15.555584Z","iopub.status.idle":"2023-01-10T21:37:15.657295Z","shell.execute_reply.started":"2023-01-10T21:37:15.555548Z","shell.execute_reply":"2023-01-10T21:37:15.655989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the images and their predictions\nfig, axes = plt.subplots(1, len(img_paths), figsize=(12,12))\n\nfor i in range(len(img_paths)):\n    ax = axes[i]\n    ax.imshow(images[i])\n    ax.axis('off')\n    prediction = predictions[i]\n    breed = breeds[np.argmax(prediction)]\n    ax.set_title(breed)\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-10T21:37:46.656478Z","iopub.execute_input":"2023-01-10T21:37:46.656890Z","iopub.status.idle":"2023-01-10T21:37:46.986285Z","shell.execute_reply.started":"2023-01-10T21:37:46.656856Z","shell.execute_reply":"2023-01-10T21:37:46.985114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}