{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":106372,"databundleVersionId":12864984,"sourceType":"competition"}],"dockerImageVersionId":31041,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-07-03T11:30:29.938728Z","iopub.execute_input":"2025-07-03T11:30:29.939061Z","iopub.status.idle":"2025-07-03T11:30:48.132465Z","shell.execute_reply.started":"2025-07-03T11:30:29.939036Z","shell.execute_reply":"2025-07-03T11:30:48.131017Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport matplotlib.pyplot as plt\n\n# Base directory\ndirectory = '/kaggle/input/2025-bamboo-summer-competiton-dl-pr/train'\n\n# Read CSV\ndf = pd.read_csv('/kaggle/input/2025-bamboo-summer-competiton-dl-pr/train.csv')\n\n# Encode labels\nle = LabelEncoder()\ndf['label_encoded'] = le.fit_transform(df['label'])\n\n# Train-validation split\ntrain_df, val_df = train_test_split(df, test_size=0.2, stratify=df['label_encoded'], random_state=42)\n\n# Create tf.data.Dataset\ntrain_ds = tf.data.Dataset.from_tensor_slices((train_df['filename'].values, train_df['label_encoded'].values))\nval_ds   = tf.data.Dataset.from_tensor_slices((val_df['filename'].values, val_df['label_encoded'].values))\n\n# Load image from path\ndef load_image(filename, label):\n    image_path = tf.strings.join([directory, filename], separator='/')\n    image = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image, channels=3)\n    return image, label\n\n# Data augmentation function\ndef data_augmentation(image):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_brightness(image, max_delta=0.1)\n    image = tf.image.random_contrast(image, 0.8, 1.2)\n    return image\n\n# Preprocessing for training (with augmentation)\ndef process_train(image, label):\n    image = tf.image.resize(image, (256, 256))\n    image = tf.cast(image, tf.float32) / 255.0\n    image = data_augmentation(image)\n    return image, label\n\n# Preprocessing for validation (no augmentation)\ndef process_val(image, label):\n    image = tf.image.resize(image, (256, 256))\n    image = tf.cast(image, tf.float32) / 255.0\n    return image, label\n\n# Constants\nBATCH_SIZE = 32\nAUTOTUNE = tf.data.AUTOTUNE\n\n# Apply pipeline\ntrain_ds = train_ds.map(load_image, num_parallel_calls=AUTOTUNE)\ntrain_ds = train_ds.map(process_train, num_parallel_calls=AUTOTUNE)\ntrain_ds = train_ds.shuffle(1000).batch(BATCH_SIZE).prefetch(AUTOTUNE)\n\nval_ds = val_ds.map(load_image, num_parallel_calls=AUTOTUNE)\nval_ds = val_ds.map(process_val, num_parallel_calls=AUTOTUNE)\nval_ds = val_ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:19:56.106053Z","iopub.execute_input":"2025-07-05T12:19:56.106226Z","iopub.status.idle":"2025-07-05T12:20:22.582810Z","shell.execute_reply.started":"2025-07-05T12:19:56.106211Z","shell.execute_reply":"2025-07-05T12:20:22.582077Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dir = '/kaggle/input/2025-bamboo-summer-competiton-dl-pr/test'\ntest_df = pd.read_csv('/kaggle/input/2025-bamboo-summer-competiton-dl-pr/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:20:22.584182Z","iopub.execute_input":"2025-07-05T12:20:22.584426Z","iopub.status.idle":"2025-07-05T12:20:22.593425Z","shell.execute_reply.started":"2025-07-05T12:20:22.584409Z","shell.execute_reply":"2025-07-05T12:20:22.592807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create tf.data.Dataset from filenames\ntest_ds = tf.data.Dataset.from_tensor_slices(test_df['filename'].values)\n\n# Test image loader and processor (same size & normalization)\ndef load_test_image(filepath):\n    image_path = tf.strings.join([test_dir, filepath], separator='/')\n    image = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.image.resize(image, (256, 256))                     # Match train/val size\n    image = tf.cast(image, tf.float32) / 255.0                     # Normalize to [0,1]\n    return image\n\n# Apply preprocessing and batch\ntest_ds = test_ds.map(load_test_image, num_parallel_calls=AUTOTUNE)\ntest_ds = test_ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:20:28.648802Z","iopub.execute_input":"2025-07-05T12:20:28.649299Z","iopub.status.idle":"2025-07-05T12:20:28.707604Z","shell.execute_reply.started":"2025-07-05T12:20:28.649278Z","shell.execute_reply":"2025-07-05T12:20:28.707073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import Xception\t\t\n# Load base model\nbase_model = Xception(include_top=False, weights='imagenet', input_shape=(224, 224, 3))\nbase_model.layers","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:20:32.108650Z","iopub.execute_input":"2025-07-05T12:20:32.109274Z","iopub.status.idle":"2025-07-05T12:20:35.525163Z","shell.execute_reply.started":"2025-07-05T12:20:32.109250Z","shell.execute_reply":"2025-07-05T12:20:35.524490Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import Xception\t\nfrom tensorflow.keras import layers, models, optimizers\nfrom tensorflow.keras.layers import Flatten\n\n# Load base model\nbase_model = Xception(include_top=False, weights='imagenet', input_shape=(256, 256, 3))\n\n\ntrainable = False\nfor layer in base_model.layers:\n    if 'block14' in layer.name:\n        layer.trainable = True\n    else:\n        layer.trainable = trainable\n        \n# Build model\nmodel = models.Sequential([\n    base_model,\n    # layers.GlobalAveragePooling2D()\n    layers.Flatten(),\n    layers.Dense(256, activation='relu'),\n    layers.Dropout(0.3),\n    layers.Dense(len(le.classes_), activation='softmax')\n])\n\n# Compile with a lower learning rate for fine-tuning\nmodel.compile(\n    optimizer=optimizers.Adam(learning_rate=1e-5),\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:24:13.229678Z","iopub.execute_input":"2025-07-05T12:24:13.230003Z","iopub.status.idle":"2025-07-05T12:24:14.373161Z","shell.execute_reply.started":"2025-07-05T12:24:13.229983Z","shell.execute_reply":"2025-07-05T12:24:14.372604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\n\ncallbacks = [\n    EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True),\n    ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2),\n    ModelCheckpoint('best_model.h5', save_best_only=True)\n]\n\nhistory = model.fit(train_ds, validation_data=val_ds, epochs=50, callbacks=callbacks)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:26:11.010744Z","iopub.execute_input":"2025-07-05T12:26:11.011361Z","iopub.status.idle":"2025-07-05T12:47:58.730891Z","shell.execute_reply.started":"2025-07-05T12:26:11.011337Z","shell.execute_reply":"2025-07-05T12:47:58.730282Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds = model.predict(test_ds)  # shape: (num_samples, num_classes)\npred_labels = tf.argmax(preds, axis=1).numpy()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:48:38.490181Z","iopub.execute_input":"2025-07-05T12:48:38.490797Z","iopub.status.idle":"2025-07-05T12:48:56.444859Z","shell.execute_reply.started":"2025-07-05T12:48:38.490751Z","shell.execute_reply":"2025-07-05T12:48:56.444294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# pred_labels: [3, 0, 1, 4, ...]\n# Decode them back to original class names\nclass_names = le.inverse_transform(pred_labels)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:49:02.020257Z","iopub.execute_input":"2025-07-05T12:49:02.020537Z","iopub.status.idle":"2025-07-05T12:49:02.025452Z","shell.execute_reply.started":"2025-07-05T12:49:02.020518Z","shell.execute_reply":"2025-07-05T12:49:02.024623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df = pd.read_csv('/kaggle/input/2025-bamboo-summer-competiton-dl-pr/test.csv')\n\nsubmission = pd.DataFrame({\n    'filename': test_df['filename'],\n    'label': class_names  # These should be the predicted class names\n})\n\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:49:05.080155Z","iopub.execute_input":"2025-07-05T12:49:05.080884Z","iopub.status.idle":"2025-07-05T12:49:05.100219Z","shell.execute_reply.started":"2025-07-05T12:49:05.080858Z","shell.execute_reply":"2025-07-05T12:49:05.099561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:49:08.938085Z","iopub.execute_input":"2025-07-05T12:49:08.938590Z","iopub.status.idle":"2025-07-05T12:49:08.959822Z","shell.execute_reply.started":"2025-07-05T12:49:08.938566Z","shell.execute_reply":"2025-07-05T12:49:08.959165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-05T12:49:12.279762Z","iopub.execute_input":"2025-07-05T12:49:12.280473Z","iopub.status.idle":"2025-07-05T12:49:12.286834Z","shell.execute_reply.started":"2025-07-05T12:49:12.280449Z","shell.execute_reply":"2025-07-05T12:49:12.286149Z"}},"outputs":[],"execution_count":null}]}