{"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":"none","dataSources":[{"sourceId":112509,"databundleVersionId":14254895,"sourceType":"competition"},{"sourceId":13673754,"sourceType":"datasetVersion","datasetId":8694449}],"dockerImageVersionId":31192,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nimport glob\ntf.random.set_seed(42)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-11-10T03:59:42.187825Z","iopub.execute_input":"2025-11-10T03:59:42.188164Z","iopub.status.idle":"2025-11-10T03:59:42.193786Z","shell.execute_reply.started":"2025-11-10T03:59:42.188139Z","shell.execute_reply":"2025-11-10T03:59:42.192581Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Auto-select best model\nmodel_files = glob.glob('*.keras') + glob.glob('biomass_model*.keras')\nMODEL_PATH = '/kaggle/input/jp-csiro-model/biomass_model_final_fullsize_progressive (1).keras'\nPREDICTION_SIZE = (224, 224)\n\n# Try to find model files\nfor priority in ['final', 'stage4', 'stage3', 'stage2', 'fullsize']:\n    matches = [f for f in model_files if priority in f.lower()]\n    if matches:\n        MODEL_PATH = matches[0]\n        try:\n            temp_model = tf.keras.models.load_model(MODEL_PATH)\n            PREDICTION_SIZE = temp_model.input_shape[1:3]\n            del temp_model\n            break\n        except:\n            continue\n\nif MODEL_PATH is None:\n    print(\"Available files:\", glob.glob('*'))\n    print(\"Available .keras files:\", model_files)\n    raise FileNotFoundError(\"No valid .keras model file found. Please ensure your trained model is in the current directory.\")\n\ntarget_names = ['Dry_Clover_g', 'Dry_Dead_g', 'Dry_Green_g', 'Dry_Total_g', 'GDM_g']\nprint(f\"Using: {MODEL_PATH}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-10T04:05:58.210204Z","iopub.execute_input":"2025-11-10T04:05:58.211037Z","iopub.status.idle":"2025-11-10T04:05:58.219298Z","shell.execute_reply.started":"2025-11-10T04:05:58.211011Z","shell.execute_reply":"2025-11-10T04:05:58.218394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def preprocess_image(image_path, target_size=(224, 224)):\n    try:\n        img = load_img(f'csiro-biomass/{image_path}', target_size=target_size)\n        return img_to_array(img) / 255.0\n    except:\n        return np.zeros(target_size + (3,))\n\n# Load model and test data with error handling\ntry:\n    model = tf.keras.models.load_model(MODEL_PATH)\n    print(f\"Model loaded successfully: {MODEL_PATH}\")\nexcept Exception as e:\n    print(f\"Error loading model: {e}\")\n    print(\"Current directory contents:\", glob.glob('*'))\n    raise\n\ntry:\n    test_df = pd.read_csv('/kaggle/input/csiro-biomass/test.csv')\n    print(f\"Test data loaded: {len(test_df)} rows\")\nexcept Exception as e:\n    print(f\"Error loading test data: {e}\")\n    print(\"Looking for test.csv in:\", glob.glob('*/test.csv'))\n    raise","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-10T04:07:03.556974Z","iopub.execute_input":"2025-11-10T04:07:03.557325Z","iopub.status.idle":"2025-11-10T04:07:04.226102Z","shell.execute_reply.started":"2025-11-10T04:07:03.557301Z","shell.execute_reply":"2025-11-10T04:07:04.225068Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Generate predictions\npredictions = []\nunique_images = test_df['image_path'].unique()\n\nfor image_path in unique_images:\n    img = preprocess_image(image_path, PREDICTION_SIZE)\n    pred = model.predict(np.expand_dims(img, axis=0), verbose=0)\n    base_sample_id = image_path.replace('test/', '').replace('.jpg', '')\n    \n    for i, target_name in enumerate(target_names):\n        sample_id = f\"{base_sample_id}__{target_name}\"\n        predictions.append({\n            'sample_id': sample_id,\n            'target': max(0, float(pred[i][0][0]))\n        })","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-10T04:07:46.049163Z","iopub.execute_input":"2025-11-10T04:07:46.050321Z","iopub.status.idle":"2025-11-10T04:07:46.175752Z","shell.execute_reply.started":"2025-11-10T04:07:46.050290Z","shell.execute_reply":"2025-11-10T04:07:46.174812Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_df = pd.DataFrame(predictions).sort_values('sample_id').reset_index(drop=True)\nsubmission_df.to_csv('biomass_predictions.csv', index=False)\nprint(f\"Complete: {len(submission_df)} predictions saved to biomass_predictions.csv\")\nprint(submission_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-10T04:08:06.243687Z","iopub.execute_input":"2025-11-10T04:08:06.244767Z","iopub.status.idle":"2025-11-10T04:08:06.266947Z","shell.execute_reply.started":"2025-11-10T04:08:06.244732Z","shell.execute_reply":"2025-11-10T04:08:06.265878Z"}},"outputs":[],"execution_count":null}]}