{"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":"gpu","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":655872,"sourceType":"modelInstanceVersion","isSourceIdPinned":false,"modelInstanceId":495713,"modelId":511111}],"dockerImageVersionId":31192,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<h4>\n    This is a notebook made for submission to the Cassava Leaf Disease Competition.\n    It uses a fine-tuned EfficientNetB0 model, trained in \n    <a href=\"https://www.kaggle.com/code/mehdiqanbari/cassava-leaf-disease-efficientnetb0-training\">This</a> notebook.\n    You can find this trained model's weights <a href=\"https://www.kaggle.com/models/mehdiqanbari/efficientnetb0-cassava-finetuned/\">Here</a>.\n</h4>","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers import Adam","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BATCH_SIZE = 16\nIMG_SIZE = (224, 224)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def build_model():\n    base_model = EfficientNetB0(weights=None, include_top=False)\n\n    model = Sequential([\n        tf.keras.layers.Input(shape=(*IMG_SIZE, 3)),\n        base_model,\n        GlobalAveragePooling2D(),\n        Dense(5, activation='softmax')\n    ])\n\n    model.compile(\n        optimizer=Adam(learning_rate=1e-3),\n        loss='categorical_crossentropy',\n        metrics=['accuracy']\n    )\n    return model\n\nmodel = build_model()\nmodel.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.load_weights(\"/kaggle/input/efficientnetb0-cassava-finetuned/tensorflow2/default/1/best_model.keras\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_dir = '/kaggle/input/cassava-leaf-disease-classification/test_images/'\ntest_df = pd.DataFrame({'image_path': [os.path.join(test_dir, f) for f in os.listdir(test_dir)]})\ntest_df['image_id'] = test_df['image_path'].apply(lambda x: os.path.basename(x))\n\ntest_generator = test_datagen.flow_from_dataframe(\n    test_df,\n    x_col='image_path',\n    y_col=None,\n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=None,\n    shuffle=False\n)\n\n# Predict\npredictions = model.predict(test_generator)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Submission\nsubmission = pd.DataFrame({'image_id': test_df['image_id'], 'label': predicted_labels})\nsubmission.to_csv('submission.csv', index=False)\nprint('Submission file created!')","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}