{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":7327,"databundleVersionId":861871,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nimport pandas as pd\nimport os\n\nIMAGE_DIR = '/kaggle/input/dog-breed-identification/train'\nCSV_PATH = '/kaggle/input/dog-breed-identification/labels.csv'\n\n\nlabels_df = pd.read_csv(CSV_PATH)\n\n\n# Prepare the DataFrame: Append '.jpg' to the image IDs\n# This is crucial for flow_from_dataframe to match the filenames in the directory\nlabels_df['id'] = labels_df['id'] + '.jpg'\n\n# Define Constants\nIMG_SIZE = 224\nBATCH_SIZE = 16\nNUM_CLASSES = labels_df['breed'].nunique() # Automatically determine the number of classes\n\nprint(f\"Total images loaded: {len(labels_df)}\")\nprint(f\"Number of classes: {NUM_CLASSES}\")\nprint(f\"Image directory: {IMAGE_DIR}\")\nprint(\"-\" * 50)\n\n\n# Initialize the ImageDataGenerator with augmentation and normalization\ndatagen = ImageDataGenerator(\n    rescale=1.0 / 255,      # Normalize pixel values\n    rotation_range=20,\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,\n    validation_split=0.3    # Reserve 30% for validation\n)\n\n# Training data generator\ntrain_generator = datagen.flow_from_dataframe(\n    dataframe=labels_df,\n    directory=IMAGE_DIR,    \n    x_col='id',\n    y_col='breed',\n    target_size=(IMG_SIZE, IMG_SIZE),\n    batch_size=BATCH_SIZE,\n    class_mode='categorical',\n    subset='training'\n)\n\n# Validation data generator\nval_generator = datagen.flow_from_dataframe(\n    dataframe=labels_df,\n    directory=IMAGE_DIR,    # Using your defined image path\n    x_col='id',\n    y_col='breed',\n    target_size=(IMG_SIZE, IMG_SIZE),\n    batch_size=BATCH_SIZE,\n    class_mode='categorical',\n    subset='validation'\n)\n\nprint(f\"Training batches: {len(train_generator)}\")\nprint(f\"Validation batches: {len(val_generator)}\")\nprint(\"-\" * 50)\n\n\n# Simple Sequential CNN Model\nmodel = Sequential([\n    # Input Layer\n    Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)),\n    MaxPooling2D((2, 2)),\n    \n    # Block 2\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    \n    # Block 3\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    \n    # Block 4 (More complex)\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Dropout(0.3),\n    \n    # Classifier Head\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.5),\n    Dense(NUM_CLASSES, activation='softmax') # Output layer\n])\n\n# Model Compilation\nmodel.compile(\n    optimizer=Adam(learning_rate=0.001),\n    loss='categorical_crossentropy',\n    metrics=['accuracy']\n)\n\n# Print model summary\nmodel.summary()\n\n\n# Model Training\nprint(\"Starting Model Training...\")\nhistory = model.fit(\n    train_generator,\n    epochs=20, # Set your desired number of training epochs\n    validation_data=val_generator,\n    verbose=1\n)\n\nprint(\"Training complete.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-10T17:52:23.183299Z","iopub.execute_input":"2025-10-10T17:52:23.183944Z","iopub.status.idle":"2025-10-10T18:33:24.726346Z","shell.execute_reply.started":"2025-10-10T17:52:23.183920Z","shell.execute_reply":"2025-10-10T18:33:24.725540Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\n\n# --- PATHS (Using the paths you previously provided) ---\nTEST_DIR = '/kaggle/input/dog-breed-identification/test' \nSAMPLE_SUBMISSION_PATH = '/kaggle/input/dog-breed-identification/sample_submission.csv'\nIMG_SIZE = 224\nBATCH_SIZE = 16\n\n# 1. PREPARE TEST DATA LIST\n# Load the sample submission file to get the image IDs in the required order.\nsubmission_df = pd.read_csv(SAMPLE_SUBMISSION_PATH)\n\n# Create a DataFrame of filenames (ID + .jpg) for the generator\ntest_df = pd.DataFrame({'id': submission_df['id'] + '.jpg'})\n\n\n# 2. CREATE TEST GENERATOR (No shuffle, no augmentation, just scaling)\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    directory=TEST_DIR,\n    x_col='id',\n    y_col=None,            # IMPORTANT: No labels for the test set\n    target_size=(IMG_SIZE, IMG_SIZE),\n    batch_size=BATCH_SIZE,\n    class_mode=None,       # IMPORTANT: Set to None for prediction/inference\n    shuffle=False          # IMPORTANT: Must be False to maintain file order\n)\n\n# 3. GENERATE PREDICTIONS\nprint(\"Generating predictions...\")\nprobabilities = model.predict(test_generator, verbose=1)\n\n\n# 4. CREATE FINAL SUBMISSION FILE\n# Get the class names in the exact order the model was trained on\nclass_names = list(train_generator.class_indices.keys())\n\n# Create a new DataFrame with the prediction probabilities and correct column headers\nsubmission_output = pd.DataFrame(probabilities, columns=class_names)\n\n# Re-insert the original 'id' column from the sample submission file (without the .jpg)\nsubmission_output.insert(0, 'id', submission_df['id'])\n\n# Save the final CSV file\nsubmission_file_name = 'submission.csv'\nsubmission_output.to_csv(submission_file_name, index=False)\n\nprint(f\"First 5 rows:\\n{submission_output.head()}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-10T18:33:36.835004Z","iopub.execute_input":"2025-10-10T18:33:36.835624Z","iopub.status.idle":"2025-10-10T18:35:19.171881Z","shell.execute_reply.started":"2025-10-10T18:33:36.835601Z","shell.execute_reply":"2025-10-10T18:35:19.171206Z"}},"outputs":[],"execution_count":null}]}