{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":61938,"databundleVersionId":6698770,"sourceType":"competition"}],"dockerImageVersionId":30580,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Import necessary libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import InceptionV3\nfrom keras.models import Sequential\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\n\n# Set constants\n#input_dir = '/kaggle/input/dog-breed-identification-data/'\ninput_dir = '/kaggle/input/dog-breed-identification-data/'\n\nimage_dir = os.path.join(input_dir, 'train')\nlabels_path = os.path.join(input_dir, 'labels.csv')\n\n# Load labels\nlabels_df = pd.read_csv(labels_path)\nbreed_labels = labels_df['breed']\nnum_classes = len(breed_labels.unique())\n\n\n\n\n\n\n\n# Import necessary libraries\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport os\n\n# Load labels from CSV\nlabels_df = pd.read_csv('/kaggle/input/dog-breed-identification-data/labels.csv')  # Update with your actual path\n\n# Split data into training and validation sets\ntrain_df, valid_df = train_test_split(labels_df, test_size=0.2, random_state=42)\ntrain_df['id'] = train_df['id'].astype(str) + '.jpg'\nvalid_df['id'] = valid_df['id'].astype(str) + '.jpg'\n\n# Define paths\ntrain_data_dir = '/kaggle/input/dog-breed-identification-data/train'  # Update with your actual path\ntest_data_dir = '/kaggle/input/dog-breed-identification-data/test'  # Update with your actual path\n\n# Data augmentation to improve model performance\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True)\n\n\n\n# Load and preprocess images\ntrain_generator = train_datagen.flow_from_dataframe(dataframe=train_df,\n                                                 directory=image_dir,\n                                                 x_col=\"id\",\n                                                 y_col=\"breed\",\n                                                 target_size=(128, 128),\n                                                 batch_size=32,\n                                                 class_mode='categorical')\n\n\n# Create a pre-trained InceptionV3 model\nbase_model = InceptionV3(weights='imagenet', include_top=False)\n\n# Add custom layers for classification\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dense(num_classes, activation='softmax'))\n\n# Compile the model\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nmodel.fit(train_generator, epochs=30)\n\n# Save the model for later use\nmodel.save('/kaggle/working/dog_breed_classifier.h5')\n\nimport pandas as pd\nfrom keras.utils import load_img, img_to_array\nimport numpy as np\nfrom keras.models import load_model\n\n# Save the model for later use\nmodel.save('/kaggle/working/dog_breed_classifier.h5')\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-10T08:54:29.357678Z","iopub.execute_input":"2023-11-10T08:54:29.358196Z","iopub.status.idle":"2023-11-10T09:00:43.780397Z","shell.execute_reply.started":"2023-11-10T08:54:29.358155Z","shell.execute_reply":"2023-11-10T09:00:43.779365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import load_model\n\n# Function to plot images with predicted labels\ndef plot_images_with_predictions(model, datagen, num_images=5):\n    # Generate a batch of images from the training set\n    for batch in datagen:\n        images, labels = batch\n        break\n\n    # Make predictions on the batch\n    predictions = model.predict(images)\n\n    # Get class labels and decode them\n    class_labels = list(datagen.class_indices.keys())\n    decoded_labels = [class_labels[np.argmax(pred)] for pred in predictions]\n\n    # Plot the images with their predicted labels\n    plt.figure(figsize=(15, 7))\n    for i in range(num_images):\n        plt.subplot(1, num_images, i + 1)\n        plt.imshow(images[i])\n        plt.title(f'Pred: {decoded_labels[i]}\\nTrue: {class_labels[np.argmax(labels[i])]}')\n        plt.axis('off')\n    plt.show()\n\n    \nmodel =  load_model('/kaggle/working/dog_breed_classifier.h5')\n\n# Plot images with predictions\nplot_images_with_predictions(model,train_generator)","metadata":{"execution":{"iopub.status.busy":"2023-11-10T09:00:43.783461Z","iopub.execute_input":"2023-11-10T09:00:43.783797Z","iopub.status.idle":"2023-11-10T09:00:50.692387Z","shell.execute_reply.started":"2023-11-10T09:00:43.783770Z","shell.execute_reply":"2023-11-10T09:00:50.691468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom keras.utils import load_img, img_to_array\nimport numpy as np\nfrom keras.models import load_model\n\n# Load the test data\ntest_data_dir = '/kaggle/input/dog-breed-identification-data/test'  # Replace with the path to your test data\ntest_filenames = os.listdir(test_data_dir)\n\n# Reduced test sets for quick check\n#test_filenames = test_filenames[1:201]\n\nprint(labels_path)\nprint(labels_df)\n# df = pd.DataFrame(labels_path)\n#ransposed_column = pd.DataFrame(df['breed']).transpose()\ntransposed_column = pd.DataFrame(labels_df['breed']).transpose()\n\ncol = []\n\nfor dog_names in transposed_column.values[0]:\n            col.append(dog_names)\n        \n\nunique_col = np.unique(col)\ncol_1= [\"id\"]\nresult_array = np.concatenate((col_1,unique_col))\npredictions_df = pd.DataFrame(columns=result_array)\n\nmodel = load_model('/kaggle/working/dog_breed_classifier.h5')\n\nfor filename in test_filenames:\n    img_path = os.path.join(test_data_dir, filename)\n    img = load_img(img_path, target_size=(128, 128))\n    img_array = img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n\n    # Make predictions\n    predictions = model.predict(img_array)\n\n    # Get the breed names\n    breed_names = list(train_generator.class_indices.keys())\n\n    # Create a dictionary for the predictions\n    prediction_dict = {'id': filename.split('.')[0]}\n    for i, breed_name in enumerate(breed_names):\n        prediction_dict[breed_name] = predictions[0][i]\n\n    # Append the predictions to the DataFrame\n    predictions_df.loc[len(predictions_df)] = prediction_dict\n\n\n# Save the predictions to a CSV file\npredictions_df.to_csv('/kaggle/working/Submissions.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2023-11-10T09:00:50.693837Z","iopub.execute_input":"2023-11-10T09:00:50.694177Z","iopub.status.idle":"2023-11-10T09:17:33.985930Z","shell.execute_reply.started":"2023-11-10T09:00:50.694148Z","shell.execute_reply":"2023-11-10T09:17:33.984884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}