{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":131587,"databundleVersionId":15786880}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom sklearn.metrics import confusion_matrix\n\ntrain_dir = \"/kaggle/input/competitions/cs-460-muffin-vs-chihuahua-classification-challenge/train\"\ntest_dir = \"/kaggle/input/competitions/cs-460-muffin-vs-chihuahua-classification-challenge/kaggle_test_final\"\nsolution_path = \"/kaggle/input/competitions/cs-460-muffin-vs-chihuahua-classification-challenge/test_solution_01.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T09:19:28.823569Z","iopub.execute_input":"2026-04-19T09:19:28.824483Z","iopub.status.idle":"2026-04-19T09:19:58.68363Z","shell.execute_reply.started":"2026-04-19T09:19:28.824449Z","shell.execute_reply":"2026-04-19T09:19:58.682598Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications.resnet50 import preprocess_input\n\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n    train_dir,\n    validation_split=0.2,\n    subset=\"training\",\n    seed=42,\n    image_size=img_size,\n    batch_size=batch_size\n)\n\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n    train_dir,\n    validation_split=0.2,\n    subset=\"validation\",\n    seed=42,\n    image_size=img_size,\n    batch_size=batch_size\n)\n\nclass_names = train_ds.class_names\n\ndef preprocess(x, y):\n    return preprocess_input(x), y\n\ntrain_ds = train_ds.map(preprocess)\nval_ds = val_ds.map(preprocess)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:31:29.186999Z","iopub.execute_input":"2026-04-19T12:31:29.187329Z","iopub.status.idle":"2026-04-19T12:31:31.391957Z","shell.execute_reply.started":"2026-04-19T12:31:29.187304Z","shell.execute_reply":"2026-04-19T12:31:31.391314Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"AUTOTUNE = tf.data.AUTOTUNE\n\ntrain_ds = train_ds.prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.prefetch(buffer_size=AUTOTUNE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:31:31.39317Z","iopub.execute_input":"2026-04-19T12:31:31.393528Z","iopub.status.idle":"2026-04-19T12:31:31.400074Z","shell.execute_reply.started":"2026-04-19T12:31:31.393504Z","shell.execute_reply":"2026-04-19T12:31:31.399132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n    tf.keras.layers.RandomFlip(\"horizontal\"),\n    tf.keras.layers.RandomRotation(0.25),\n    tf.keras.layers.RandomZoom(0.1)\n])\n\nbase_model = tf.keras.applications.ResNet50(\n    input_shape=(224,224,3),\n    include_top=False,\n    weights=\"imagenet\"\n)\n\nbase_model.trainable = False\n\ninputs = tf.keras.Input(shape=(224,224,3))\nx = data_augmentation(inputs)\nx = base_model(x, training=False)\nx = tf.keras.layers.GlobalAveragePooling2D()(x)\n\nx = tf.keras.layers.Dense(256, activation=\"relu\")(x)\nx = tf.keras.layers.Dropout(0.5)(x)\nx = tf.keras.layers.Dense(64, activation=\"relu\")(x)\n\noutputs = tf.keras.layers.Dense(1, activation=\"sigmoid\")(x)\n\nmodel = tf.keras.Model(inputs, outputs)\n\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(1e-4),\n    loss=\"binary_crossentropy\",\n    metrics=[\"accuracy\"]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:31:31.401343Z","iopub.execute_input":"2026-04-19T12:31:31.401695Z","iopub.status.idle":"2026-04-19T12:31:34.510453Z","shell.execute_reply.started":"2026-04-19T12:31:31.401659Z","shell.execute_reply":"2026-04-19T12:31:34.509589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    train_ds,\n    validation_data=val_ds,\n    epochs=20\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:31:34.512091Z","iopub.execute_input":"2026-04-19T12:31:34.512315Z","iopub.status.idle":"2026-04-19T12:36:15.425087Z","shell.execute_reply.started":"2026-04-19T12:31:34.512294Z","shell.execute_reply":"2026-04-19T12:36:15.424071Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(base_model.layers)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.8839Z","iopub.execute_input":"2026-04-19T12:39:00.884165Z","iopub.status.idle":"2026-04-19T12:39:00.897366Z","shell.execute_reply.started":"2026-04-19T12:39:00.884136Z","shell.execute_reply":"2026-04-19T12:39:00.896736Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model.trainable = True\n\nfor layer in base_model.layers[:-100]:\n    layer.trainable = False\n\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(1e-5),\n    loss=\"binary_crossentropy\",\n    metrics=[\"accuracy\"]\n)\n\nhistory_fine = model.fit(\n    train_ds,\n    validation_data=val_ds,\n    epochs=5\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:36:15.426271Z","iopub.execute_input":"2026-04-19T12:36:15.426598Z","iopub.status.idle":"2026-04-19T12:38:44.828595Z","shell.execute_reply.started":"2026-04-19T12:36:15.426564Z","shell.execute_reply":"2026-04-19T12:38:44.827566Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure()\nplt.plot(history.history[\"accuracy\"], label=\"train\")\nplt.plot(history.history[\"val_accuracy\"], label=\"val\")\nplt.legend()\nplt.title(\"Accuracy\")\nplt.show()\n\nplt.figure()\nplt.plot(history.history[\"loss\"], label=\"train\")\nplt.plot(history.history[\"val_loss\"], label=\"val\")\nplt.legend()\nplt.title(\"Loss\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:38:44.829832Z","iopub.execute_input":"2026-04-19T12:38:44.830238Z","iopub.status.idle":"2026-04-19T12:38:45.122914Z","shell.execute_reply.started":"2026-04-19T12:38:44.830211Z","shell.execute_reply":"2026-04-19T12:38:45.121936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"solution_df = pd.read_csv(solution_path)\nsolution_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:38:45.129351Z","iopub.execute_input":"2026-04-19T12:38:45.129704Z","iopub.status.idle":"2026-04-19T12:38:45.145053Z","shell.execute_reply.started":"2026-04-19T12:38:45.129679Z","shell.execute_reply":"2026-04-19T12:38:45.14429Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = []\nlabels = []\n\nfor _, row in solution_df.iterrows():\n    img_path = os.path.join(test_dir, row[\"ID\"])\n    img = tf.keras.preprocessing.image.load_img(img_path, target_size=img_size)\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = preprocess_input(img)\n    test_images.append(img)\n    labels.append(1 if row[\"Label\"] == \"muffin\" else 0)\n\nX_test = np.array(test_images)\ny_true = np.array(labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:38:45.146119Z","iopub.execute_input":"2026-04-19T12:38:45.146478Z","iopub.status.idle":"2026-04-19T12:38:52.89716Z","shell.execute_reply.started":"2026-04-19T12:38:45.146454Z","shell.execute_reply":"2026-04-19T12:38:52.896282Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds = model.predict(X_test)\ny_pred = (preds > 0.5).astype(int).reshape(-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:38:52.898448Z","iopub.execute_input":"2026-04-19T12:38:52.898794Z","iopub.status.idle":"2026-04-19T12:39:00.692109Z","shell.execute_reply.started":"2026-04-19T12:38:52.898756Z","shell.execute_reply":"2026-04-19T12:39:00.691367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import ConfusionMatrixDisplay\n\ncm_display = ConfusionMatrixDisplay.from_predictions(\n    y_true,\n    y_pred,\n    display_labels=[\"chihuahua\", \"muffin\"],\n    cmap=\"Blues\"\n)\nplt.title(\"Confusion Matrix\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.694724Z","iopub.execute_input":"2026-04-19T12:39:00.695024Z","iopub.status.idle":"2026-04-19T12:39:00.83308Z","shell.execute_reply.started":"2026-04-19T12:39:00.694994Z","shell.execute_reply":"2026-04-19T12:39:00.832458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy = np.mean(y_true == y_pred)\naccuracy","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.8339Z","iopub.execute_input":"2026-04-19T12:39:00.83425Z","iopub.status.idle":"2026-04-19T12:39:00.839586Z","shell.execute_reply.started":"2026-04-19T12:39:00.834216Z","shell.execute_reply":"2026-04-19T12:39:00.838907Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(class_names)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.841011Z","iopub.execute_input":"2026-04-19T12:39:00.84121Z","iopub.status.idle":"2026-04-19T12:39:00.852364Z","shell.execute_reply.started":"2026-04-19T12:39:00.841191Z","shell.execute_reply":"2026-04-19T12:39:00.851737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_labels = [\"muffin\" if p == 1 else \"chihuahua\" for p in y_pred]\n\nsubmission = pd.DataFrame({\n    \"ID\": solution_df[\"ID\"],\n    \"Label\": pred_labels\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)\n\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.853612Z","iopub.execute_input":"2026-04-19T12:39:00.853911Z","iopub.status.idle":"2026-04-19T12:39:00.87533Z","shell.execute_reply.started":"2026-04-19T12:39:00.85388Z","shell.execute_reply":"2026-04-19T12:39:00.874311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.Label.value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T12:39:00.876524Z","iopub.execute_input":"2026-04-19T12:39:00.877031Z","iopub.status.idle":"2026-04-19T12:39:00.88301Z","shell.execute_reply.started":"2026-04-19T12:39:00.877008Z","shell.execute_reply":"2026-04-19T12:39:00.882356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}