{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30918,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-03-24T08:47:06.711507Z","iopub.execute_input":"2025-03-24T08:47:06.711861Z","iopub.status.idle":"2025-03-24T08:47:12.404417Z","shell.execute_reply.started":"2025-03-24T08:47:06.711831Z","shell.execute_reply":"2025-03-24T08:47:12.395138Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Machine Learning & AI for Wheat Classification\nDeep learning models (CNNs, RNNs, transformers) for wheat detection\n\nAI-driven image segmentation and classification\n\nFusion of multiple data sources (satellite, UAV, ground sensors) using ML models\n\nAutomated wheat growth stage classification using AI","metadata":{}},{"cell_type":"code","source":"import os\nimport time\nimport shutil\nimport random\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torchvision\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor, FasterRCNN\nfrom torchvision.models.detection.backbone_utils import resnet_fpn_backbone\nfrom tqdm.notebook import tqdm\n\nimport albumentations\nfrom albumentations import *\nfrom albumentations.pytorch.transforms import ToTensorV2\nimport cv2\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nimport seaborn as sns\n%matplotlib inline\nprint('Ready...')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:48:34.336931Z","iopub.execute_input":"2025-03-24T08:48:34.337319Z","iopub.status.idle":"2025-03-24T08:48:45.935043Z","shell.execute_reply.started":"2025-03-24T08:48:34.337285Z","shell.execute_reply":"2025-03-24T08:48:45.933915Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" load data and simple EDA","metadata":{}},{"cell_type":"code","source":"DATA_DIR  = '../input/global-wheat-detection/train/'\nTEST_DIR  = '../input/global-wheat-detection/test/'\ntrain_df_path = '../input/global-wheat-detection/train.csv'\ntest_df_path = '../input/global-wheat-detection/sample_submission.csv'\nList_Data_dir = os.listdir(DATA_DIR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:49:40.408293Z","iopub.execute_input":"2025-03-24T08:49:40.408755Z","iopub.status.idle":"2025-03-24T08:49:40.415378Z","shell.execute_reply.started":"2025-03-24T08:49:40.40872Z","shell.execute_reply":"2025-03-24T08:49:40.414163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"raw = pd.read_csv(train_df_path)\nraw","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:49:54.00009Z","iopub.execute_input":"2025-03-24T08:49:54.000488Z","iopub.status.idle":"2025-03-24T08:49:54.36149Z","shell.execute_reply.started":"2025-03-24T08:49:54.000456Z","shell.execute_reply":"2025-03-24T08:49:54.360328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#check empty data\nraw.isnull().any().any()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:50:26.199328Z","iopub.execute_input":"2025-03-24T08:50:26.199801Z","iopub.status.idle":"2025-03-24T08:50:26.231681Z","shell.execute_reply.started":"2025-03-24T08:50:26.199765Z","shell.execute_reply":"2025-03-24T08:50:26.230681Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"raw.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:50:43.714711Z","iopub.execute_input":"2025-03-24T08:50:43.715023Z","iopub.status.idle":"2025-03-24T08:50:43.766086Z","shell.execute_reply.started":"2025-03-24T08:50:43.715001Z","shell.execute_reply":"2025-03-24T08:50:43.765131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"raw.describe","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:50:51.412098Z","iopub.execute_input":"2025-03-24T08:50:51.412503Z","iopub.status.idle":"2025-03-24T08:50:51.421463Z","shell.execute_reply.started":"2025-03-24T08:50:51.412469Z","shell.execute_reply":"2025-03-24T08:50:51.420365Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Based on the data in the table, we can see there are only two tables (width and height), Why? because from the data we have there are only two columns of type number (Dtype --> number (int/float). From this table, it is known that all our images are 1024 x 1024. Ok, let's see how many that pictures we have\n\n ","metadata":{}},{"cell_type":"code","source":"print(f'Total number of train images: {raw.image_id.nunique()}')\nprint(f'Total number of test images: {len(os.listdir(TEST_DIR))}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:51:47.296915Z","iopub.execute_input":"2025-03-24T08:51:47.297404Z","iopub.status.idle":"2025-03-24T08:51:47.316974Z","shell.execute_reply.started":"2025-03-24T08:51:47.297362Z","shell.execute_reply":"2025-03-24T08:51:47.315667Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" plt.figure(figsize=(15,8))\nplt.title('Wheat Distribution', fontsize= 20)\nsns.countplot(x=\"source\", data=raw)\n\n# based on the chart, there are seven types of wheat from images data, with the most types 'ethz_1' and the least is 'inrae_1'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:52:09.401619Z","iopub.execute_input":"2025-03-24T08:52:09.401992Z","iopub.status.idle":"2025-03-24T08:52:09.897175Z","shell.execute_reply.started":"2025-03-24T08:52:09.401962Z","shell.execute_reply":"2025-03-24T08:52:09.895809Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#lets visualize some images\nfig, ax = plt.subplots(1, 2, figsize = (24, 24))\nax = ax.flatten()\nimg_path = os.path.join(DATA_DIR, 'b6ab77fd7' + '.jpg')\nimg_path2 = os.path.join(DATA_DIR, '5e0747034' + '.jpg')\n\nimage = cv2.imread(img_path, cv2.IMREAD_COLOR)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\nimage /= 255.0\n    \nax[0].set_title('Image')\nax[0].imshow(image)\n    \nimage2 = cv2.imread(img_path2, cv2.IMREAD_COLOR)\nimage2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB).astype(np.float32)\nimage2 /= 255.0\n\nax[1].set_title('Image')\nax[1].imshow(image2)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:52:47.706302Z","iopub.execute_input":"2025-03-24T08:52:47.706755Z","iopub.status.idle":"2025-03-24T08:52:50.073098Z","shell.execute_reply.started":"2025-03-24T08:52:47.706715Z","shell.execute_reply":"2025-03-24T08:52:50.070943Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Extract bbox column to xmin, ymin, width, height, then create xmax, ymax, and area columns\n\nraw[['xmin','ymin','w','h']] = pd.DataFrame(raw.bbox.str.strip('[]').str.split(',').tolist()).astype(float)\nraw['xmax'], raw['ymax'], raw['area'] = raw['xmin'] + raw['w'], raw['ymin'] + raw['h'], raw['w'] * raw['h']\nraw.drop(['bbox'], axis=1, inplace= True)\nraw","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:53:20.028748Z","iopub.execute_input":"2025-03-24T08:53:20.02913Z","iopub.status.idle":"2025-03-24T08:53:20.652774Z","shell.execute_reply.started":"2025-03-24T08:53:20.029102Z","shell.execute_reply":"2025-03-24T08:53:20.651686Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"In object detection, we usually use a boundary box to describe the target location. The boundary box is a rectangular box that can be determined by the x and y axis coordinates in the upper-left corner and the x and y axis coordinates in the lower-right corner of the rectangle.\n\n ","metadata":{}},{"cell_type":"markdown","source":"Let's look at some random images with boundary boxes","metadata":{}},{"cell_type":"code","source":"def show_image(image_id):\n    \n    fig, ax = plt.subplots(1, 2, figsize = (24, 24))\n    ax = ax.flatten()\n    \n    bbox = raw[raw['image_id'] == image_id ]\n    img_path = os.path.join(DATA_DIR, image_id + '.jpg')\n    \n    image = cv2.imread(img_path, cv2.IMREAD_COLOR)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n    image /= 255.0\n    image2 = image\n    \n    ax[0].set_title('Original Image')\n    ax[0].imshow(image)\n    \n    for idx, row in bbox.iterrows():\n        x1 = row['xmin']\n        y1 = row['ymin']\n        x2 = row['xmax']\n        y2 = row['ymax']\n        label = row['source']\n        \n        cv2.rectangle(image2, (int(x1),int(y1)), (int(x2),int(y2)), (255,255,255), 2)\n        font = cv2.FONT_HERSHEY_SIMPLEX\n        cv2.putText(image2, label, (int(x1),int(y1-10)), font, 1, (255,255,255), 2)\n    \n    ax[1].set_title('Image with Bondary Box')\n    ax[1].imshow(image2)\n\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:54:26.180842Z","iopub.execute_input":"2025-03-24T08:54:26.181371Z","iopub.status.idle":"2025-03-24T08:54:26.193256Z","shell.execute_reply.started":"2025-03-24T08:54:26.18133Z","shell.execute_reply":"2025-03-24T08:54:26.19083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"show_image(raw.image_id.unique()[91])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:54:48.916607Z","iopub.execute_input":"2025-03-24T08:54:48.916959Z","iopub.status.idle":"2025-03-24T08:54:50.55097Z","shell.execute_reply.started":"2025-03-24T08:54:48.916933Z","shell.execute_reply":"2025-03-24T08:54:50.549443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"show_image(raw.image_id.unique()[1231])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:55:13.107987Z","iopub.execute_input":"2025-03-24T08:55:13.10837Z","iopub.status.idle":"2025-03-24T08:55:14.748298Z","shell.execute_reply.started":"2025-03-24T08:55:13.10834Z","shell.execute_reply":"2025-03-24T08:55:14.746768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"show_image(raw.image_id.unique()[3121])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T08:55:31.991044Z","iopub.execute_input":"2025-03-24T08:55:31.991407Z","iopub.status.idle":"2025-03-24T08:55:33.736384Z","shell.execute_reply.started":"2025-03-24T08:55:31.991381Z","shell.execute_reply":"2025-03-24T08:55:33.734882Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Deep Analysis of Machine Learning & AI for Wheat Classification\nAdvancements in AI and machine learning (ML) have revolutionized wheat classification and monitoring, enabling high-accuracy crop detection, disease identification, and yield prediction. This section explores deep learning models, AI-driven segmentation and classification, fusion of multi-source data, and automated wheat growth stage classification in detail.","metadata":{}},{"cell_type":"markdown","source":"1. # Deep Learning Models for Wheat Detection\nDeep learning models like CNNs, RNNs, and Transformers have significantly improved wheat detection accuracy. These models analyze spectral, spatial, and temporal data from satellite and UAV imagery to classify wheat fields.\n\nA.**** ## Convolutional Neural Networks (CNNs)\nCNNs are widely used for image-based wheat detection and classification due to their ability to extract spatial features.\n\nPopular CNN Architectures:\n\nResNet: Used for high-accuracy wheat classification.\n\nU-Net: Applied for wheat field segmentation.\n\nEfficientNet: Lightweight, high-performance model for real-time wheat detection.\n\nUse Case: CNNs applied to Sentinel-2 and UAV images achieve high precision in distinguishing wheat from other crops.","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"raw.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:02:24.944122Z","iopub.execute_input":"2025-03-24T09:02:24.944579Z","iopub.status.idle":"2025-03-24T09:02:24.961768Z","shell.execute_reply.started":"2025-03-24T09:02:24.944527Z","shell.execute_reply":"2025-03-24T09:02:24.960391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# data preprocessing\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nimport torch\nimport torchvision.transforms as transforms\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\n \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:03:23.052295Z","iopub.execute_input":"2025-03-24T09:03:23.052747Z","iopub.status.idle":"2025-03-24T09:03:43.891638Z","shell.execute_reply.started":"2025-03-24T09:03:23.052711Z","shell.execute_reply":"2025-03-24T09:03:43.890503Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define image size and batch size\nIMG_SIZE = (224, 224)\nBATCH_SIZE = 32\n\n# Load dataset CSV file\nraw = pd.read_csv(train_df_path)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:04:35.341378Z","iopub.execute_input":"2025-03-24T09:04:35.342134Z","iopub.status.idle":"2025-03-24T09:04:35.527266Z","shell.execute_reply.started":"2025-03-24T09:04:35.342098Z","shell.execute_reply":"2025-03-24T09:04:35.526164Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualize Sample Images\ndef show_sample_images():\n    fig, ax = plt.subplots(3, 3, figsize=(10, 10))\n    image_files = os.listdir(\"../input/global-wheat-detection/train\")[:9]\n    \n    for i, img_file in enumerate(image_files):\n        img = cv2.imread(f\"../input/global-wheat-detection/train/{img_file}\")\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        ax[i//3, i%3].imshow(img)\n        ax[i//3, i%3].axis(\"off\")\n    \n    plt.show()\n\nshow_sample_images()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:07:11.565345Z","iopub.execute_input":"2025-03-24T09:07:11.565769Z","iopub.status.idle":"2025-03-24T09:07:13.770385Z","shell.execute_reply.started":"2025-03-24T09:07:11.565735Z","shell.execute_reply":"2025-03-24T09:07:13.769106Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"3.# Implement ResNet for Wheat Classification#\nusing tensorflow/keras\n","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.models import Model\n\n# Load pre-trained ResNet50 model\nbase_model = ResNet50(weights=\"imagenet\", include_top=False, input_shape=(224, 224, 3))\n\n# Freeze base model layers\nfor layer in base_model.layers:\n    layer.trainable = False\n\n# Add classification head\nx = Flatten()(base_model.output)\nx = Dense(512, activation=\"relu\")(x)\nx = Dropout(0.5)(x)\nx = Dense(1, activation=\"sigmoid\")(x)  # Binary classification\n\nmodel = Model(inputs=base_model.input, outputs=x)\nmodel.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n\n# Model Summary\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:09:53.307797Z","iopub.execute_input":"2025-03-24T09:09:53.308347Z","iopub.status.idle":"2025-03-24T09:09:59.868728Z","shell.execute_reply.started":"2025-03-24T09:09:53.308302Z","shell.execute_reply":"2025-03-24T09:09:59.866157Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Data Augmentation\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n\n ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:21:21.129843Z","iopub.execute_input":"2025-03-24T09:21:21.130209Z","iopub.status.idle":"2025-03-24T09:21:21.135452Z","shell.execute_reply.started":"2025-03-24T09:21:21.130181Z","shell.execute_reply":"2025-03-24T09:21:21.134267Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":" # Data Augmentation\ntrain_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)\ntrain_generator = train_datagen.flow_from_directory(\n    \"../input/global-wheat-detection/train\", target_size=(224, 224), batch_size=32, class_mode=\"binary\", subset=\"training\")\nval_generator = train_datagen.flow_from_directory(\n    \"../input/global-wheat-detection/train\", target_size=(224, 224), batch_size=32, class_mode=\"binary\", subset=\"validation\")\n\n# Train ResNet\nhistory = model.fit(train_generator, validation_data=val_generator, epochs=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:23:04.372464Z","iopub.execute_input":"2025-03-24T09:23:04.372993Z","iopub.status.idle":"2025-03-24T09:23:06.726466Z","shell.execute_reply.started":"2025-03-24T09:23:04.372953Z","shell.execute_reply":"2025-03-24T09:23:06.724967Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# 4.Implement U-Net for Wheat Field Segmentation\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, concatenate, Input\n\ndef build_unet(input_shape=(256, 256, 3)):\n    inputs = Input(input_shape)\n\n    # Encoder\n    c1 = Conv2D(64, (3, 3), activation=\"relu\", padding=\"same\")(inputs)\n    p1 = MaxPooling2D((2, 2))(c1)\n\n    c2 = Conv2D(128, (3, 3), activation=\"relu\", padding=\"same\")(p1)\n    p2 = MaxPooling2D((2, 2))(c2)\n\n    # Bottleneck\n    c3 = Conv2D(256, (3, 3), activation=\"relu\", padding=\"same\")(p2)\n\n    # Decoder\n    u1 = UpSampling2D((2, 2))(c3)\n    c4 = Conv2D(128, (3, 3), activation=\"relu\", padding=\"same\")(u1)\n    \n    u2 = UpSampling2D((2, 2))(c4)\n    c5 = Conv2D(64, (3, 3), activation=\"relu\", padding=\"same\")(u2)\n\n    outputs = Conv2D(1, (1, 1), activation=\"sigmoid\")(c5)\n\n    model = Model(inputs, outputs)\n    model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n    \n    return model\n\n# Create U-Net model\nunet_model = build_unet()\nunet_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:23:45.426722Z","iopub.execute_input":"2025-03-24T09:23:45.427091Z","iopub.status.idle":"2025-03-24T09:23:45.529252Z","shell.execute_reply.started":"2025-03-24T09:23:45.427062Z","shell.execute_reply":"2025-03-24T09:23:45.528135Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Train U-Net","metadata":{}},{"cell_type":"code","source":"# Load segmentation masks (Modify dataset accordingly)\ntrain_masks = train_generator.flow_from_directory(\n    \"../input/global-wheat-detection/sample_submission\", target_size=(256, 256), batch_size=32, class_mode=\"binary\")\n\n# Train U-Net model\nunet_model.fit(train_generator, train_masks, validation_data=(val_generator, train_masks), epochs=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:25:53.84756Z","iopub.execute_input":"2025-03-24T09:25:53.847933Z","iopub.status.idle":"2025-03-24T09:25:53.878787Z","shell.execute_reply.started":"2025-03-24T09:25:53.847906Z","shell.execute_reply":"2025-03-24T09:25:53.877189Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"5. Implement EfficientNet for Real-Time Wheat Detection\n","metadata":{}},{"cell_type":"markdown","source":"EfficientNet is a lightweight CNN used for real-time wheat detection.\n\nEfficientNet Model\n ","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import EfficientNetB0\n\n# Load pre-trained EfficientNet model\nbase_model = EfficientNetB0(weights=\"imagenet\", include_top=False, input_shape=(224, 224, 3))\n\n# Add custom classification head\nx = Flatten()(base_model.output)\nx = Dense(256, activation=\"relu\")(x)\nx = Dropout(0.5)(x)\nx = Dense(1, activation=\"sigmoid\")(x)  # Binary classification\n\nefficientnet_model = Model(inputs=base_model.input, outputs=x)\nefficientnet_model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n\nefficientnet_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:27:39.483672Z","iopub.execute_input":"2025-03-24T09:27:39.48406Z","iopub.status.idle":"2025-03-24T09:27:41.157606Z","shell.execute_reply.started":"2025-03-24T09:27:39.484031Z","shell.execute_reply":"2025-03-24T09:27:41.15613Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Recurrent Neural Networks (RNNs)\n1.RNNs, especially Long Short-Term Memory (LSTM) networks, process time-series wheat growth data.\n\n2.Application: Predicting wheat growth trends from multi-temporal satellite imagery.\n\n3.Limitations: RNNs struggle with long-term dependencies, making hybrid CNN-LSTM models more effective.","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout, Conv1D, MaxPooling1D, Flatten\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:35:18.224072Z","iopub.execute_input":"2025-03-24T09:35:18.224557Z","iopub.status.idle":"2025-03-24T09:35:18.231455Z","shell.execute_reply.started":"2025-03-24T09:35:18.224467Z","shell.execute_reply":"2025-03-24T09:35:18.229361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_DIR  = '../input/global-wheat-detection/train/'\nTEST_DIR  = '../input/global-wheat-detection/test/'\ntrain_df_path = '../input/global-wheat-detection/train.csv'\ntest_df_path = '../input/global-wheat-detection/sample_submission.csv'\nList_Data_dir = os.listdir(DATA_DIR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:41:38.644934Z","iopub.execute_input":"2025-03-24T09:41:38.645308Z","iopub.status.idle":"2025-03-24T09:41:38.653655Z","shell.execute_reply.started":"2025-03-24T09:41:38.645279Z","shell.execute_reply":"2025-03-24T09:41:38.652132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('../input/global-wheat-detection/train.csv')\n#df1 = pd.read_csv('../input/global-wheat-detection/test/.csv')\ndf2 = pd.read_csv('../input/global-wheat-detection/train.csv')\ndf3= pd.read_csv('../input/global-wheat-detection/sample_submission.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:45:40.275501Z","iopub.execute_input":"2025-03-24T09:45:40.275954Z","iopub.status.idle":"2025-03-24T09:45:40.660793Z","shell.execute_reply.started":"2025-03-24T09:45:40.275921Z","shell.execute_reply":"2025-03-24T09:45:40.659676Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"df3.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:46:11.036123Z","iopub.execute_input":"2025-03-24T09:46:11.036531Z","iopub.status.idle":"2025-03-24T09:46:11.047185Z","shell.execute_reply.started":"2025-03-24T09:46:11.036502Z","shell.execute_reply":"2025-03-24T09:46:11.046143Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"🌾#  ## Wheat Growth Prediction using RNN (LSTM) & Satellite Data\nWe will use Long Short-Term Memory (LSTM) networks to analyze multi-temporal wheat growth data from Kaggle datasets. Since RNNs struggle with long-term dependencies, we will also explore CNN-LSTM hybrid models for better feature extraction.# ","metadata":{}},{"cell_type":"code","source":"# Load the dataset (modify the path based on the Kaggle dataset)\ndataset_path = \"../input/global-wheat-detection/sample_submission.csv\"\ndf = pd.read_csv(dataset_path)\n\n# Display dataset sample\nprint(df.head())\n\n# Assume columns: ['date', 'NDVI', 'temperature', 'rainfall', 'wheat_yield']\n# Convert date to datetime format\n#df['date'] = pd.to_datetime(df['date'])\n\n# Sort data by date\n#df = df.sort_values('date')\n\n# Select features for time series prediction\nfeatures = ['width', 'height', 'image_id']\ntarget = 'source'\n\n# Normalize the data\nscaler = MinMaxScaler()\ndf[features + [target]] = scaler.fit_transform(df[features + [target]])\n\n# Create sequences for LSTM (time step = 10 days)\ndef create_sequences(data, target_col, time_steps=10):\n    sequences = []\n    labels = []\n    for i in range(len(data) - time_steps):\n        sequences.append(data[i : i + time_steps])\n        labels.append(data[i + time_steps, target_col])\n    return np.array(sequences), np.array(labels)\n\n# Convert data to numpy\ndata_array = df[features + [target]].values\n\n# Create input sequences\ntime_steps = 10\nX, y = create_sequences(data_array, target_col=-1, time_steps=time_steps)\n\n# Split into training and testing\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\nprint(f\"Training Samples: {X_train.shape}, Testing Samples: {X_test.shape}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-24T09:41:06.823472Z","iopub.execute_input":"2025-03-24T09:41:06.823845Z","iopub.status.idle":"2025-03-24T09:41:06.872739Z","shell.execute_reply.started":"2025-03-24T09:41:06.823821Z","shell.execute_reply":"2025-03-24T09:41:06.871302Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}