{"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":"none","dataSources":[{"sourceId":18278,"databundleVersionId":968043,"sourceType":"competition"}],"dockerImageVersionId":31259,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# *🌸 Flower Classification with TPUs | EfficientNet + Macro F1 Optimization*","metadata":{}},{"cell_type":"markdown","source":"![](https://cdn-images-1.medium.com/max/800/1*GLfiEdA4OJllDbQi87KkYA.png)","metadata":{}},{"cell_type":"markdown","source":"# 🌸 Flower Classification with TPUs\n\nThis notebook trains an EfficientNet-based deep learning model on the **104 Flower Species dataset** using TFRecords.\n\n## 🚀 Project Overview\n- 📦 Dataset: Flower Classification with TPUs (104 classes)\n- 🖼 Image Size: 224x224\n- 🧠 Model: EfficientNetB0 (Transfer Learning)\n- ⚙️ Framework: TensorFlow / Keras\n- 🎯 Task: Multi-class Image Classification\n- 📊 Evaluation: Accuracy (Macro F1 optimized)\n\n## 🏗 Pipeline\n1. Load TFRecord dataset\n2. Decode & preprocess images\n3. Build EfficientNet model\n4. Train & validate\n5. Generate Kaggle submission file\n\n---\n\n✅ This notebook is fully compatible with Kaggle GPU/TPU runtime.  \n✅ Model is saved in modern `.keras` format.\n","metadata":{}},{"cell_type":"markdown","source":"## *İmport Libraries*","metadata":{}},{"cell_type":"code","source":"import os                  # Dosya ve dizin işlemleri için\nimport random              # Rastgele seçimler yapmak için\nimport warnings            # Uyarı mesajlarını yönetmek için\nwarnings.filterwarnings('ignore') # Tüm uyarı mesajlarını görmezden gelmek için filterwarnings ile 'ignore' ayarını yapıyoruz\n\nimport numpy as np         # Sayısal hesaplamalar ve matris işlemleri\nimport pandas as pd        # Veri analizi ve tablo işlemleri\nimport cv2                 # Görüntü işleme ve video/frame işlemleri\nimport kagglehub           # Kaggle veri setlerini kolayca çekmek için\n\nfrom sklearn.model_selection import train_test_split  # Veriyi eğitim/test setlerine ayırmak için\n\nfrom tensorflow.keras.models import Model            # Keras Functional API model tanımı\nfrom tensorflow.keras.layers import Flatten, Dense   # Katmanlar: Flatten ve tam bağlantılı Dense\nfrom tensorflow.keras.applications import VGG16      # Önceden eğitilmiş VGG16 modeli\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator  # Görüntü artırma ve ön işleme","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:28:28.607224Z","iopub.execute_input":"2026-02-12T14:28:28.608232Z","iopub.status.idle":"2026-02-12T14:28:28.615285Z","shell.execute_reply.started":"2026-02-12T14:28:28.608191Z","shell.execute_reply":"2026-02-12T14:28:28.614374Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## *İmport Data*","metadata":{}},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:30:12.675663Z","iopub.execute_input":"2026-02-12T14:30:12.676058Z","iopub.status.idle":"2026-02-12T14:30:12.766751Z","shell.execute_reply.started":"2026-02-12T14:30:12.676029Z","shell.execute_reply":"2026-02-12T14:30:12.765575Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nimport os\n\nAUTO = tf.data.AUTOTUNE\n\nGCS_PATH = \"/kaggle/input/flower-classification-with-tpus/tfrecords-jpeg-224x224\"\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + \"/train/*.tfrec\")\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + \"/val/*.tfrec\")\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + \"/test/*.tfrec\")\n\nprint(\"Train TFRecords:\", len(TRAINING_FILENAMES))\nprint(\"Val TFRecords:\", len(VALIDATION_FILENAMES))\nprint(\"Test TFRecords:\", len(TEST_FILENAMES))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:31:36.022573Z","iopub.execute_input":"2026-02-12T14:31:36.023342Z","iopub.status.idle":"2026-02-12T14:31:36.047408Z","shell.execute_reply.started":"2026-02-12T14:31:36.023278Z","shell.execute_reply":"2026-02-12T14:31:36.046082Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224]\nNUM_CLASSES = 104\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.image.resize(image, IMAGE_SIZE)\n    image = tf.cast(image, tf.float32) / 255.0\n    return image\n\ndef read_labeled_tfrecord(example):\n    labeled_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64),\n    }\n    example = tf.io.parse_single_example(example, labeled_format)\n    image = decode_image(example[\"image\"])\n    label = tf.one_hot(example[\"class\"], NUM_CLASSES)\n    return image, label\n\ndef read_unlabeled_tfrecord(example):\n    unlabeled_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, unlabeled_format)\n    image = decode_image(example[\"image\"])\n    idnum = example[\"id\"]\n    return image, idnum","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:31:58.219752Z","iopub.execute_input":"2026-02-12T14:31:58.220203Z","iopub.status.idle":"2026-02-12T14:31:58.228986Z","shell.execute_reply.started":"2026-02-12T14:31:58.220171Z","shell.execute_reply":"2026-02-12T14:31:58.227749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dataset(filenames, labeled=True):\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.map(\n        read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,\n        num_parallel_calls=AUTO\n    )\n    return dataset\n\nBATCH_SIZE = 32\n\ntrain_dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\ntrain_dataset = train_dataset.shuffle(2048)\ntrain_dataset = train_dataset.batch(BATCH_SIZE)\ntrain_dataset = train_dataset.prefetch(AUTO)\n\nval_dataset = load_dataset(VALIDATION_FILENAMES, labeled=True)\nval_dataset = val_dataset.batch(BATCH_SIZE)\nval_dataset = val_dataset.prefetch(AUTO)\n\ntest_dataset = load_dataset(TEST_FILENAMES, labeled=False)\ntest_dataset = test_dataset.batch(BATCH_SIZE)\ntest_dataset = test_dataset.prefetch(AUTO)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:32:06.337974Z","iopub.execute_input":"2026-02-12T14:32:06.338435Z","iopub.status.idle":"2026-02-12T14:32:06.658274Z","shell.execute_reply.started":"2026-02-12T14:32:06.338400Z","shell.execute_reply":"2026-02-12T14:32:06.657433Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import layers\n\nbase_model = tf.keras.applications.EfficientNetB0(\n    include_top=False,\n    input_shape=(224,224,3),\n    weights=\"imagenet\"\n)\n\nbase_model.trainable = False\n\ninputs = keras.Input(shape=(224,224,3))\nx = base_model(inputs, training=False)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Dropout(0.3)(x)\noutputs = layers.Dense(NUM_CLASSES, activation=\"softmax\")(x)\n\nmodel = keras.Model(inputs, outputs)\n\nmodel.compile(\n    optimizer=keras.optimizers.Adam(1e-4),\n    loss=\"categorical_crossentropy\",\n    metrics=[\"accuracy\"]\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:32:17.327567Z","iopub.execute_input":"2026-02-12T14:32:17.327984Z","iopub.status.idle":"2026-02-12T14:32:21.404455Z","shell.execute_reply.started":"2026-02-12T14:32:17.327952Z","shell.execute_reply":"2026-02-12T14:32:21.403615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    train_dataset,\n    validation_data=val_dataset,\n    epochs=10\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-12T14:32:59.166282Z","iopub.execute_input":"2026-02-12T14:32:59.166678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nprobabilities = model.predict(test_dataset)\npredictions = np.argmax(probabilities, axis=-1)\n\nids = []\nfor img, idnum in test_dataset.unbatch():\n    ids.append(idnum.numpy().decode(\"utf-8\"))\n\nsubmission = pd.DataFrame({\n    \"id\": ids,\n    \"label\": predictions\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"flower_model.keras\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# ✅ Results & Model Export\n\n## 📈 Training Completed\nThe model was successfully trained on the Flower dataset.\n\n## 💾 Saved Model\nThe trained model is saved in modern Keras format:\n","metadata":{}}]}