Introduction

The demand for increased agricultural production is urgent due to the growing global population. Supply and demand will occasionally be misaligned, making resource management critical. Managing and maintaining human and capital resources remains a significant challenge in improving agricultural productivity. The application of intelligent agriculture facilitates food production, resource management, and employment generation1. Predictive modelling plays a crucial role in influencing farmers’ prior knowledge of its implementation. This approach also highlights the challenges of integrating modern farming techniques with existing methods. Quantitative and statistical techniques can enhance the current agricultural system. IoT faces challenges in agriculture, irrigation, and plant disease detection, particularly when deploying drones2.

IoT, a fundamental component of modern society, has expanded rapidly. One way to address the challenges of establishing seamless connectivity between devices is by integrating WSN into IoT systems. These technologies can be applied in precision agriculture to collect field data, analyze it, and make timely farming decisions. Precision farming processes benefit from enhanced field monitoring using these methods. Farmers must make numerous decisions regarding harvesting, irrigation, and other agricultural practices3. With IoT-enabled sensors placed in crop fields, it is possible to monitor conditions and gather data on variables such as humidity, temperature, and soil nutrients. Sensors have limited power reserves as they are battery-operated. They continuously collect and transmit data, depleting their finite energy resources. A sensor (commonly referred to as a “mote”) typically operates on a battery and requires a similar amount of initial energy4. Since these sensors are deployed in various environments, it is impractical to frequently replace their batteries. In intelligent precision farming using IoT and WSNs, operations must be conducted in an energy-efficient manner due to the limited power supply of these devices. To accurately report affected crop areas in precision farming, sensors must be aware of their spatial context. As sensors are susceptible to a wide range of attacks, particularly network-based and physical threats, securing localization techniques is essential in this context5.

Crop recommendation systems play a crucial role in modern precision agriculture by leveraging data-driven approaches to optimize crop selection. These systems analyse various environmental and soil parameters, such as pH levels, humidity, precipitation, temperature, and nutrient content, to provide tailored recommendations for farmers6. By integrating real-time sensor data, satellite imagery, and advanced statistical models, these systems ensure improved crop yields, minimized resource wastage, and enhanced sustainability. Unlike existing experience-based decision-making, AI-driven crop recommendation models help farmers make informed choices based on predictive analytics, significantly improving agricultural productivity7. The adoption of Machine Learning (ML) techniques such as Deep Learning (DL) and ensemble algorithms further enhanced the accuracy of crop prediction. Models such as neural networks, decision trees, and federated learning approaches enable the system to learn from large datasets collected across different agricultural regions. By identifying complex patterns and relationships between environmental factors and crop performance, these models optimize planting strategies, irrigation schedules, and fertilization plans8. Integrating AI-powered recommendation systems with automated pest control, water management, and market demand forecasting helps bridge the gap between conventional and smart farming practices, ensuring higher efficiency and profitability. As agriculture continues to evolve with emerging technologies, smart crop recommendation systems will play a vital role in promoting sustainable farming9. These systems not only reduce the risk of crop failure help in the judicious use of water, fertilizers, and other agricultural inputs. Incorporating block chain technology can enhance data security and transparency ensuring reliable recommendations based on authenticated data sources. With continuous advancements in IoT, AI, and big data analytics, precision agriculture powered by intelligent crop recommendation models will be instrumental in securing global food production and addressing the challenges of climate change10. Existing signal detection techniques are hindered by environmental noise and a lack of message diversity, as they primarily rely on preset rules and parameters to detect illicit signals. As a result, struggle to adapt and learn new forms of illegal signals. DL can adjust to various tasks and data types making it a more flexible and robust solution. Federated learning is a subset of DL offers a privacy-preserving approach to utilizing channel feature information for training neural networks in channel identification11. DL algorithms exhibit superior adaptability and generalization across diverse external environments learning from a variety of intelligent devices operating on widely distributed large datasets. To enhance identification accuracy, this study employs DL techniques to address the challenges of channel identification in smart agricultural settings involve complex environments, diverse device functionalities and varied spatial distributions12. Vision Transformers (ViT) had a significant impact on computer vision leading an increasing number of researchers to adopt them as their network backbone or integrate their principles into various algorithms. By leveraging self-attention mechanisms, effectively capture long-range dependencies in signals, such as spatial and temporal sequences, enhancing the model’s ability to analyze complex patterns. ViT perform exceptionally well in processing multiscale signals, efficiently adapting to signal patterns of varying frequencies and scales13. During training, autonomously learn representations that align with the unique characteristics of the signals, further improving analytical accuracy. ML enables algorithms to utilize multiple processing layers, representing information at different levels of abstraction. In agriculture, DL is widely applied in image processing for classification, object detection for disease identification, weed recognition, soil analysis, and plant disease detection, enhancing precision farming techniques14.

The proposed study introduces several novel aspects in the domain of smart agriculture and IoT-enabled monitoring. Firstly, it presents an Improved Weighted Quantum Whale Optimization (IWQWO) algorithm that integrates quantum-inspired mechanisms with adaptive weighting, enhancing node clustering, routing efficiency, and anomaly detection in Wireless Sensor Networks (WSNs). Secondly, the integration of a Vision Transformer (ViT) for sensor data analysis enables effective capture of spatial-temporal relationships, ensuring high-precision environmental monitoring and intrusion detection. Thirdly, the framework combines energy-efficient and secure network design with advanced data-driven intelligence, addressing critical challenges such as high energy consumption and security vulnerabilities. Additionally, the study explores practical applications in automated irrigation, drone-assisted monitoring, and plant disease detection, bridging the gap between modern IoT technologies and traditional agricultural practices. Finally, extensive evaluations demonstrate that the proposed IWQWO-ViT model achieves superior accuracy, reliability, and cost-effectiveness, highlighting its potential as a robust solution for intelligent, secure, and sustainable agricultural automation.

Key contribution of the paper as follows:

  • Proposed IWQWO optimizes node clustering, routing efficiency, and anomaly detection in WSNs.

  • Vision Transformer effectively captures spatial-temporal sensor data for precise environmental monitoring.

  • Integrated IWQWO-ViT framework enhances intrusion detection accuracy, reducing false alarms significantly.

  • Facilitates automated irrigation, drone-assisted monitoring, and plant disease detection in agriculture.

  • Improves energy efficiency, network reliability, and cost-effectiveness in smart farming system.

Related works

Power requirements, routing algorithms, sensor node deployment, and data gathering are among the challenges that real-time WSN applications must overcome. An optimal routing protocol is essential for WSN applications to facilitate efficient communication between sensor nodes. Information transfer over wireless networks must be cost-effective, energy-efficient, fast, and durable. WSN technologies are structured into five layers: the physical layer, data link layer, transport layer, network layer, and application layer15. The design of a WSN system is guided by application-specific requirements, including network coverage area, the number of sensor nodes, data collection intervals, power consumption, lifespan, data type, and communication with the base station. WSNs have been utilized to develop precision agricultural solutions aimed at protecting crops from diseases, pests, and insects. A motion-detecting camera sensor is deployed in the field to capture images and send them to a server for further processing16. Major drawback of this model is its high energy consumption for image capture and transmission. Various types of sensors and hardware are employed for crop monitoring. A prototype has been developed using WSNs to track crop growth at each stage. In this study, sensor nodes and image processing techniques are used to non-invasively monitor crop development. The surveillance system leverages WSNs to provide real-time data on crop growth and alerts users if abnormal development is detected17. Sensor nodes are strategically placed in the field to assess actual crop resource needs, thereby minimizing resource wastage. The proposed approach incorporates fuzzy logic to optimize crop growth monitoring at each stage of development. A technique has been developed to monitor intelligent agriculture using a minimal number of sensor nodes18. Given temperature and geographic constraints, placing sensor nodes in mountainous regions remains a significant challenge. The proposed method determines the ideal locations for sensor node deployment by considering multiple factors affecting crop growth. These factors are then integrated into a mathematical framework that captures the most critical principles and characteristics of crop development19. The model is subsequently analysed to address the crop surveillance problem effectively. Developed a sensor-based farm protection system against wildlife intrusion. Sensor nodes such as radio frequency detectors, optical sensors, sound detectors, and infrared passive sensors were deployed in agricultural fields20. These sensor nodes continuously monitor the area and transmit information to the base station then forwards the data to a server for further analysis. Similarly, designed a wireless sensor-based crop monitoring system. The system determines greenhouse gas requirements based on crop models, with gas sensors detecting regular variations in greenhouse gas emissions21.

Nitrogen is the key nutrient essential for the development and advancement of sugarcane. Farmers can optimize greenhouse conditions in the field with the aid of these assessments. Employed sensor technologies in agriculture to develop an autonomous, precise placement system. This system integrated sensor node data collected from various field locations to enhance efficiency. The primary advantages of this approach included direct communication with nodes and improved detection of malfunctioning nodes22. Using WSNs, developed a soil water status monitoring system for agricultural areas to enable efficient irrigation. By utilizing real-time sensor data, effective farm management strategies were implemented. Two types of soil moisture sensors (MPS-1) and watermark sensors were tested in this system. The goal of the proposed approach was to install sensor nodes within a WSN for surveillance purposes and systematically arrange the integrated sensor networks23. After collecting information from the sensor nodes, the measurement capability and response time of the sensors in the soil layer during evaporation were analysed. This technique helps maintain minimal water stress without compromising crop development, even when water supply is limited. Crop growth is modelled using a computerized soil-crop simulation system. Estimating soil moisture remains a complex process, influenced by soil type and physical properties24. Introduced a remote irrigation control and monitoring system utilizing two separate linear motion mechanisms. The proposed method regulates water spray by connecting to a minicomputer via relays and a wireless web server. It determines the precise amount of water required per hectare for crop irrigation. To ensure accurate water distribution, the system continuously monitors pressure sensors, sensing nodes, and water flow. By comparing the desired and actual water depths, this method also detects faults in water management25. To minimize water application errors, a model based on water movement patterns was developed. For precision farming, proposed a wireless sensor-based, fuzzy logic-driven autonomous irrigation management system. A sensor node was deployed in the agricultural field to continuously monitor environmental variables such as soil temperature, soil moisture, air temperature, and humidity levels26. The data is transmitted to the base station for processing whenever the sensor values exceed a predefined threshold or based on user requirements. To ensure optimal signal strength across the cultivated field, a region-based static clustering method was employed. Hybrid routing system was implemented to facilitate data transfer between sensor nodes and the base station. A fuzzy logic approach was used to identify the cluster head reducing overall power consumption27. Proposed a sensor-based advanced irrigation control system tailored to specific land conditions. This approach managed irrigation by determining the optimal timing and amount of water required for efficient crop growth. A WSN was utilized to support a software-based decision assistance system. The application leveraged Bluetooth connectivity to control sprinkler systems, providing an intuitive Graphical User Interface (GUI) for real-time field surveillance. This system enabled automated operation of field-specific irrigation sprinklers while continuously monitoring field data28.

The primary benefit of a closed-loop irrigation system is its ability to regulate water flow based on sensor data. Developed a WSN-based valve management irrigation system to optimize water distribution. In the agricultural industry, WSNs are primarily used for surveillance rather than management. The proposed design integrates wireless sensors, hardware, and software to create a cost-effective irrigation control system29. Customized firmware was developed for the valve devices, enabling direct connectivity to an internet gateway for seamless interaction with online applications. The valve regulator is powered by solar panels, ensuring sustainable energy usage. The proposed commercial irrigation system replaces manual valve controllers with automated ones, reducing labor costs and providing a direct internet connection for remote management30. Employed a wireless sensor network to develop a customizable decision support system that includes a separate closed-loop field-based irrigation system. This approach emphasizes the system’s flexibility and adaptability while leveraging philosophical reasoning to validate and refine the program’s logic. AI techniques were applied to datasets to detect sensor failures and extract new insights, enhancing agricultural surveillance31. A novel rule-based AI approach was implemented, significantly improving the system’s functionality. From an economic perspective, this proposed approach surpasses traditional agricultural methods in efficiency. Utilizing sensor technology, designed a real-time freshwater resource tracking system to minimize water wastage. The system provides comprehensive data on water usage, including date, location, and volume32. Water pipes are equipped with wireless vibration detectors to monitor water consumption. Each pipeline is fitted with a vibration sensor that detects low water flow rates, while a central water flow meter records the total water usage. This system helps farmers track water consumption for each pipeline, reducing waste and improving irrigation efficiency. The proposed technique also addresses multiple optimization challenges by calibrating water distribution and analysing various pipeline topologies33.

Fig. 1
Fig. 1The alternative text for this image may have been generated using AI.
Full size image

Proposed architecture.

Despite significant advancements in IoT-enabled smart agriculture, several critical gaps remain unaddressed. Existing Wireless Sensor Network (WSN) frameworks often suffer from high energy consumption, limited real-time processing, and security vulnerabilities, which hinder reliable environmental monitoring and intrusion detection. Existing optimization algorithms fail to effectively balance network efficiency and anomaly detection accuracy, while conventional deep learning methods struggle to capture the complex spatial-temporal patterns inherent in agricultural sensor data. Existing approaches rarely integrate energy-efficient clustering, secure routing, and precise environmental analysis into a unified framework, limiting practical applicability in large-scale smart farms. The adoption of automated irrigation, drone-assisted monitoring, and plant disease detection remains suboptimal due to fragmented implementations and inadequate predictive intelligence. These limitations highlight the need for a comprehensive, secure, and intelligent framework that combines optimized network management with advanced deep learning models to enhance sustainability, reliability, and decision-making in smart agriculture.

Materials and methods

A new hybrid technique, IWQWO with ViT, has been developed to enhance environmental surveillance and intrusion detection in intelligent farming using WSNs. Existing WSN-based farming systems face challenges such as high energy consumption, network inefficiencies, security vulnerabilities, and imprecise anomaly detection, limiting their reliability and scalability. IWQWO leverages quantum-inspired optimization with adaptive weighting to improve node clustering, route optimization, and anomaly detection, ensuring efficient energy consumption and long-term system sustainability shown in Fig. 1. The ViT enhances this framework by capturing spatial-temporal sensor data relationships enabling high-precision environmental monitoring and real-time intrusion detection with fewer false alarms. This hybrid approach optimizes sensor data processing, enhances security, and supports automated decision-making, making it a resource-efficient and eco-friendly solution for smart farming. Extensive simulations and evaluations demonstrate significant improvements in energy efficiency, network stability, and detection accuracy compared to existing methods. By integrating advanced AI with bio-inspired optimization, the IWQWO-ViT architecture offers a robust, scalable, and intelligent solution for next-generation smart agriculture, ensuring greater sustainability, operational efficiency, and security.

Dataset description

The databases used in this study are crucial for achieving environmental surveillance and intrusion detection in smart farming. The Smart Agriculture Data consists of real-time information collected from IoT-based WSNs deployed in agricultural fields shown in Table 1. These datasets include key environmental parameters such as humidity, soil moisture, temperature, light intensity, and pH levels, which are essential for monitoring field conditions, optimizing irrigation, and assessing crop health. By leveraging these datasets, the system enhances decision-making processes and overall agricultural efficiency.

Table 1 Dataset description.
Table 2 Smart agriculture data.
Table 3 IoT-based intrusion detection data.
Table 4 Atmospheric monitoring data.
Table 5 Crop recommendation data.
Table 6 Remote sensing satellite data.

This sample data includes the key attributes relevant to each aspect of the research: Smart Agriculture Data, Intrusion Detection, Atmospheric Monitoring, Crop Recommendation, and Remote Sensing. Each dataset contains timestamps, sensor values, and other critical details needed for real-time decision-making, security, and resource optimization in smart agricultural environments shown in Tables 2, 3, 4, 5 and 6.

Fig. 2
Fig. 2The alternative text for this image may have been generated using AI.
Full size image

(a) Indoor environment (Plant factory) (b) Outdoor environment (Smart Farming).

The drone’s collected data was uploaded as sensor information along with high-definition photos shown in Fig. 2(a). The robotic arm may autonomously finish planting and trimming by connecting to the drone’s information based on the requirements of the crop. The central management system receives information from smart sensors placed throughout the interior space that provide continuous tracking of the levels of light, moisture, and carbon dioxide in the atmosphere. Corresponding to the centralized management system, the plant security drone, cutting-edge agricultural machinery, and smart irrigation systems carried out pesticide spraying, field searching, crop gathering, and watering on the farmland in the outdoor setting depicted in Fig. 2 (b). Wireless networks are typically used to convey communication since various gadgets have distinct mobility statuses and might be either immobile or moving.

Fig. 3
Fig. 3The alternative text for this image may have been generated using AI.
Full size image

Proposed model for RealSmartAgri.

An analog-to-digital converter (MCP3008) enables IoT sensors to interface with a Raspberry Pi, allowing data transmission to a remote server. Once the data is collected and analysed, it is made available to farmers or end-users for informed decision-making. To facilitate accessibility, an Android application can be developed using MIT Application Inventor enabling users to retrieve data stored in a database like ThingSpeak or a cloud platform. This real-time access is essential for evaluating agricultural performance, optimizing yields, improving efficiency, and managing water resources. Figure 3 presents a procedural diagram of the RealSmartAgri surveillance system illustrating the overall structure and functionality of the RealSmartAgri agriculture monitoring framework.

Pre-processing

It is an essential step in improving ML models’ precision and effectiveness. In this study, implement IWQWO - ViT to optimize the data set for intrusion detection, environmental tracking, and smart farming recommendation systems by using processing approaches. Data augmentation approach is shown in Fig. 4 and sample images shown in Fig. 5.

Handling missing data

Real-world agricultural and atmospheric data often suffer from missing values due to sensor failures, transmission errors, and environmental interferences. Missing data is handled using a probabilistic approach.

Missing data formulation

Let \(\:{D}_{s}\) be the dataset consisting of complete data \(\:{D}_{0}\) and missing data\(\:{D}_{m}\).

$$\:{D}_{s}={D}_{0}+{D}_{m}$$
(1)

The probability of missing data P(\(\:{D}_{p}\)) given observed data \(\:{D}_{0}\) and missing data \(\:{D}_{m}\) is:

$$\:{P(D}_{p}|{D}_{0},{D}_{m})$$
(2)

Where: \(\:{D}_{p}\) the probability of missing data; H is an indicator function for missing values:

$$\:H=\:\left\{\begin{array}{c}1,\:if\:{D}_{0}\:\left(complete\:data\:present\right)\\\:0,\:if\:{D}_{m}\:\left(data\:missing\right)\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\end{array}\right.\:\:$$
(3)
Missing data imputation using quantum-optimized mean estimation

To estimate missing values, we use an Improved Weighted Quantum Mean Imputation (IWQMI):

$$\:{\widehat{D}}_{m}=\frac{1}{n}\sum\:_{x=1}^{n}{W}_{x}\times\:{D}_{x}$$
(4)

Where: \(\:{\widehat{D}}_{m}\:\)the imputed missing data, \(\:{W}_{x}\:\)the quantum weight optimization factor computed as:

$$\:{W}_{x}=\:\frac{{e}^{-\alpha\:\left|{D}_{x}-\mu\:\right|}}{\sum\:_{y=1}^{n}{e}^{-\alpha\:\left|{D}_{y}-\mu\:\right|}}$$
(5)

Where \(\:\alpha\:\) is a tunable quantum scaling factor.

Data normalization

Since sensor data and environmental readings vary in scale (e.g., temperature in Celsius, humidity in percentage, and intrusion detection signals as binary values), normalization is required.

Min-max normalization

To scale data between [0, 1]:

$$\:{D}_{normalized}=\frac{D-{D}_{min}}{{D}_{max}-{D}_{min}}\:$$
(6)

Where: \(\:{D}_{max}\) and \(\:{D}_{min}\) are the maximum and minimum values of the dataset.

Quantum-enhanced normalization

To improve the normalization process using quantum weighting:

$$\:{N}^{{\prime\:}}=2\times\:\left(\frac{N-min}{max-min}\right)-1$$
(7)

Where N’ is the normalized value.

By enhancing the extraction of characteristics and decreasing overfitting, these methods improve environmental tracking, intrusion detection, and agricultural recommendations in the setting of ViT.

Data augmentation

Rotation

Random rotations help the model learn orientation-invariant features.

$$\:{X}_{\theta\:}=X\times\:R\left(\theta\:\right)$$
(8)

Where: \(\:R\left(\theta\:\right)\) is the rotation matrix, \(\:\theta\:\) is the angle of rotation (randomly sampled, e.g., between [\(\:{-30}^{^\circ\:}\), \(\:{30}^{^\circ\:}\)]).

Flipping (horizontal & vertical)

Used to handle asymmetry in images.

$$\:{X}^{{\prime\:}}=flip\left(X\right)$$
(9)

Where: Horizontal flip: \(\:{X}^{{\prime\:}}={X}_{{i}_{max}-i}\) ; Vertical flip: \(\:{X}^{{\prime\:}}={X}_{{j}_{max}-j}\),

Scaling & cropping

Scaling changes the image size while maintaining the aspect ratio.

$$\:{X}^{{\prime\:}}=resize\left(X,\left({w}^{{\prime\:}},h{\prime\:}\right)\right)$$
(10)

Where \(\:{w}^{{\prime\:}}=s.w\) and \(\:{h}^{{\prime\:}}=s.h,\) with scale factor s.

Cropping randomly selects a region:

$$\:X{\prime\:}=X\left[i:i+{w}^{{\prime\:}},j:j+h{\prime\:}\right]$$
(11)

Where (i, j) is the starting coordinate.

Fig. 4
Fig. 4The alternative text for this image may have been generated using AI.
Full size image

No. of augmentations = 5, Input image = 1, New images generated = 45 (9 for each augmentation).

Fig. 5
Fig. 5The alternative text for this image may have been generated using AI.
Full size image

Sample images of pre-processing (a) Charlock; (b) Fat Hen; (c) Shepherd’s purse; (d) Small-flowered Cranesbill; (e) Maize.

The pre-processing procedures guarantee that smart agriculture recommendations, atmospheric inspection, and security detection are learning-optimized. Effective selection of features, normalization of data, and pertinent data extraction are all made possible by the IWQWO with ViT technology. In intelligent farming and safety applications, this technique guarantees maximum performance of the models, reduced redundancy, and improved precision.

Feature selection using recursive fisher score method

The Recursive Fisher Score (RFS) approach plays a crucial role in crop recommendation systems by selecting the most relevant features from vast agricultural datasets, including soil properties, weather conditions, and environmental factors. Identifying these key attributes is essential for making accurate and efficient crop recommendations, as they significantly influence agricultural productivity. RFS ranks the most important features for classification or prediction, allowing for the selection of an optimal subset of characteristics. This not only reduces data complexity but also enhances predictive performance.

Key benefits of RFS in c,lrop Recommendation Systems:

  • Dimensionality reduction: Agricultural datasets often contain high-dimensional features such as soil moisture, pH levels, humidity, temperature, and sunlight. RFS extracts the most discriminatory features, minimizing redundancy while preserving essential information.

  • Enhanced model efficiency: By eliminating irrelevant features, RFS reduces computational overhead, making real-time crop recommendation systems more efficient.

  • Improved predictive accuracy: Focusing on the most impactful features allows RFS to enhance crop prediction reliability, leading to better yield estimation and more region-specific recommendations.

By integrating RFS, crop recommendation models can achieve higher precision, better efficiency, and improved decision-making capabilities, ultimately benefiting farmers and agricultural stakeholders.

Step 1: Compute Fisher score for each feature

The Fisher Score for each feature \(\:{i}_{x}\) is calculated as:

$$\:F\left({i}_{x}\right)=\frac{\sum\:_{c=1}^{C}{N}_{c}{\left({\mu\:}_{c}^{x}-{\mu\:}^{x}\right)}^{2}}{\sum\:_{c=1}^{C}{N}_{c}{\left({\sigma\:}_{c}^{x}\right)}^{2}}$$
(12)

Where: \(\:F\left({i}_{x}\right)\) is the Fisher Score of feature \(\:{i}_{x}\); C is the number of crop classes; \(\:{N}_{c}\) is the number of instances of crop c; \(\:{\mu\:}_{c}^{x}\:\)is the mean of feature \(\:{i}_{x}\) for crop с; \(\:{\mu\:}^{x}\) is the global mean of feature \(\:{i}_{x}\) across all crops; \(\:{\sigma\:}_{c}^{x}\) the standard deviation of feature \(\:{i}_{x}\) for crop c.

Step 2: Apply recursive feature selection

Recursive selection of features comes next, after the calculation of every characteristic’s Fisher Score. Characteristics with lower Fisher Scores are recursively removed throughout this method.

  1. 1.

    Sort features: Sort every feature according to its \(\:F\left({i}_{x}\right)\) Fisher Score.

  2. 2.

    Choose top characteristics: To optimize the discriminative strength, begin by choosing the characteristics with the highest rating.

  3. 3.

    Remove redundant characteristics: The dataset is cleared of features with lower Fisher Scores.

  4. 4.

    Recalculate Fisher scores: After removing a feature, continue the procedure by recalculating the Fisher Scores for the remaining characteristics.

  5. 5.

    Stop criterion: When the characteristic selection offers the best categorization results, stop.

Step 3: Recursive Fisher score calculation

In each iteration of feature selection, Fisher Scores are recalculated. The process of feature elimination is recursive, and after each feature is removed, the Fisher Scores are recalculated for the remaining features. The general formula for Recursive Fisher Score is:

$$\:{F}^{(t+1)}\left({i}_{x}\right)=\frac{\sum\:_{c=1}^{C}{N}_{c}{\left({\mu\:}_{c}^{x}-{\mu\:}^{x}\right)}^{2}}{\sum\:_{c=1}^{C}{N}_{c}{\left({\sigma\:}_{c}^{x}\right)}^{2}}$$
(13)

Where \(\:{F}^{(t+1)}\left({i}_{x}\right)\) represents the Fisher Score of feature \(\:{i}_{x}\:\)at the (t + 1)th iteration, after eliminating one feature in the previous iteration.

Step 4: Build the crop recommendation model

Once the most relevant features are selected through the Recursive Fisher Score method, a machine learning model (e.g., Support Vector Machine (SVM), Random Forest, or KNN) can be trained on the dataset using these features. The model can then predict the best crops based on environmental and soil conditions.

Step 5: Model prediction for crop recommendation

Let’s say we now have a set of selected features \(\:{i}_{1},{i}_{2},\dots\:,{i}_{k}\:\)the crop recommendation model uses these features for predicting the most suitable crop. For instance, if using a Random Forest or SVM classifier, the model might make predictions based on the optimal feature set as:

$$\:\widehat{C}=f({i}_{1},{i}_{2},\dots\:,{i}_{k})\:$$
(14)

Where: \(\:\widehat{C}\) is the predicted crop class (for instance, wheat, corn, rice). \(\:{i}_{1},{i}_{2},\dots\:,{i}_{k}\) are the most relevant features selected by RFS. An effective technique for choosing the most distinguishing characteristics in agriculture datasets is the Recursive Fisher Score approach to crop choice. This approach contributes to the development of more precise and computationally successful recommendation systems by concentrating on the characteristics that most differentiate across crop classes, hence enhancing crop yield forecasts according to environmental and soil factors.

Feature extraction using ViT

Accurate extraction of characteristics is essential for crop systems that recommend crops because it allows for identifying trends in environmental information, including soil type, humidity, temperature, rainfall, and more. ViT used for extracting characteristics from multi-dimensional agricultural information by turning it into patches and processing it similar to an image shown in Fig. 6. Images undergo manipulation through several transformer layers of encoder after being treated by ViTs as a series of patches.

Fig. 6
Fig. 6The alternative text for this image may have been generated using AI.
Full size image

Feature extraction using ViT.

ViTs can learn associations between various visual elements and efficiently model worldwide context thanks to this technique concurrently captures local and global knowledge. The input picture is separated into fixed-size patches in a standard ViT structure. These patches are then encrypted and linearly embedded before being supplied into the converter and encoding layers. The model may learn a representation of the visual at various levels of abstraction thanks to its computational layers include feed-forward artificial neural networks and multi-head self-awareness techniques.

Data transformation into patches

To apply Vision Transformers for crop recommendation, we first need to transform the raw data into a suitable format. The data collected for crop recommendation can consist of various features, such as: Soil Parameters: pH, moisture level, etc. Meteorological Data: Temperature, humidity, wind speed, etc. Geographic Data: Latitude, longitude, altitude. Each of these features is treated as part of a larger “image” by dividing them into non-overlapping patches. For instance, agricultural data can be structured in grids (similar to pixels in an image), where each grid represents a region in the field. These regions are analogous to image patches. Suppose the data is in a form of a 2D array with multiple features, and we treat this data as a pseudo-image by dividing it into \(\:P\times\:P\) patches. The process can be mathematically represented as:

$$\:{Patch}_{x}=Flatten\left(X\right)\:$$
(15)

Where \(\:{X}_{x}\) represents the x-th data patch, and each patch is a feature vector corresponding to specific environmental or soil data.

Linear embedding of patches

Each patch is then linearly embedded into a fixed-size vector. The embedding is done by multiplying each flattened patch with a learnable weight matrix \(\:{W}_{embedding}\)

$$\:Patch\:{Embedding}_{x}={W}_{embedding}.{Patch}_{x}$$
(16)

The resulting vectors for each patch are then used as input for the transformer.

Positional encoding

To retain the spatial relationships (such as proximity of patches in the grid) similar to how ViT handles position in images.

$$\:Patch\:Embedding\:with\:Positional\:{Encoding}_{x}=Patch\:{Embedding}_{x}+{P}_{x}\:$$
(17)

Where, \(\:{P}_{x}\) represents the positional encoding for the xth patch.

Transformer encoder layers

In the self-attention mechanism, each patch learns to attend to the other patches based on their relevance. The attention score between patch x and patch y is calculated as:

$$\:{Attention}_{xy}=\frac{exp({Patch}_{x}\:.{Patch}_{y}^{T})\:}{\sum\:_{k}exp({Patch}_{x}\:.{Patch}_{k}^{T})}\:$$
(18)

CLS token for global features

CLS token aggregates the information from all patches.

$$Crop~\text{Re} commendation = Soft\max \left( {W_{{classifier}} .Crop~Features} \right)~$$
(19)

The output token is used as the feature vector for the entire dataset.

Feature extraction output

After passing through the transformer encoder, the final output for the crop recommendation system is the feature representation obtained from the [CLS] token. This feature vector encapsulates the high-level understanding of the input data, such as soil health, weather conditions, and geographical location. The final feature vector is used for downstream tasks like crop recommendation.

$$\:Crop\:Features={Output}_{CLS}$$
(20)

Crop recommendation

Once the features are extracted, they are used to recommend the most suitable crops for the given conditions. For instance, a simple softmax classifier could be used to recommend crops based on the extracted features:

$$\:Crop\:Recommendation=Softmax({W}_{classifier}.Crop\:Features)\:$$
(21)

Where \(\:{W}_{classifier}\) is the weight matrix used for classification.

By treating multi-dimensional agricultural data as a grid (similar to an image), ViT can extract high-level features that can be used to recommend the most suitable crops based on the environment and conditions. An inventive method that makes use of transformer models to capture dependency relationships and linkages in agriculture information involves the use of ViT for the extraction of features in crop recommendations. ViT can extract high-level characteristics from multi-dimensional agricultural information by treating it as a grid is comparable to an image. These characteristics may then be used to suggest the best crops for the specific surroundings and circumstances. Crop recommendations can become much more accurate and efficient using this method.

Fig. 7
Fig. 7The alternative text for this image may have been generated using AI.
Full size image

Intrusion detection system using improved weighted quantum whale optimization.

Improved weighted quantum Whale Optimization for intrusion detection system in smart agriculture

To protect the confidentiality and security of information, IDS are essential for spotting possible cyber-attacks and irregularities in IoT systems. In smart agriculture, IWQWO method can be a very useful tool for enhancing IDS performance. By effectively choosing characteristics, adjusting system settings, and enhancing ML systems’ ability to classify, this technique improves IDS’s capacity to identify abnormalities or intrusions.

Quantum Whale Optimization (QWO)

Quantum Whale Optimization (QWO) is inspired by the social behavior and hunting strategies of whales. It utilizes quantum computing principles to enhance optimization tasks by introducing quantum variables into the existing optimization approach. The core idea is that each whale in the pack represents a solution in the search space, and the position of the wolves is updated based on the best solutions found. The main advantage of the quantum version over classical whale optimization is its ability to explore the solution space more effectively, using superposition and quantum interference.

Position update of Whales in QWO: The position of each Whale \(\:{I}_{x}\left(t\right)\:\)at time t is updated according to the Eq. (22):

$$\:{I}_{x}\left(t+1\right)={I}_{x}\left(t\right)+\alpha\:.\left(best\:position-{I}_{x}\left(t\right)\right)+\beta\:.\left(random\:factor.{I}_{x}\left(t\right)\right)$$
(22)

Where: \(\:{I}_{x}\left(t\right)\) is the position of the x-th Whale at time t, \(\:\alpha\:\) is a scaling factor, best position refers to the best solution found so far, \(\:\beta\:\) is another scaling factor for randomness, and random factor is a random value used to promote exploration.

Improved weighted quantum Whale Optimization (IWQWO)

The WQWO enhances the basic QWO by introducing a weighting factor to adjust the importance of certain features or parameters, improving the IDS’s sensitivity to relevant patterns in intrusion detection shown in Fig. 7. IWQWO focuses on the following aspects:

  • Feature selection: The algorithm helps to select the most relevant features for intrusion detection, optimizing the input data.

  • Parameter tuning: It also tunes hyper parameters of the IDS model, such as the threshold value in anomaly detection models or the weights in classifier models.

The feature selection process in IWQWO involves assigning weights to the features based on their relevance to detecting intrusions in the system. This improves the accuracy and reduces the computational complexity of the IDS.

Position Update with Weighting Factor: The IWQWO update rule for each Whale’s position can be expressed as:

$$\:{I}_{x}\left(t+1\right)={I}_{x}\left(t\right)+\alpha\:.({W}_{best\:}.best\:position\:{I}_{x}\left(t\right))\:+\beta\:.\:(random\:factor.{I}_{x}\left(t\right))\:$$
(23)

Where: \(\:{W}_{best\:}\) is the weight factor applied to the best solution found so far.

The weight factor helps to refine the search process by prioritizing certain dimensions (features) over others based on their importance in detecting intrusions.

Feature selection using IWQWO in IDS

In the context of intrusion detection, feature selection is critical to ensuring that only the most relevant attributes of the data are used to detect anomalies. Features such as packet size, communication frequency, and source IP address may have high importance in intrusion detection tasks whereas other features might be less important and could be discarded. IWQWO performs feature selection by assigning weights to each feature. The features with the highest weights are considered most important and are retained, while those with lower weights are discarded. The fitness function for feature selection in IWQWO can be defined as:

$$\:f\left(I\right)=\sum\:_{x=1}^{N}\left({w}_{x}.{f}_{x}\right)$$
(24)

Where: f(I) is the total fitness of the feature set, \(\:{w}_{x}\) is the weight of the xth feature, \(\:{f}_{x}\) is the importance score of the xth feature. The IWQWO algorithm optimizes the weights to maximize the detection accuracy of the IDS, selecting features that contribute most to identifying intrusions.

In smart farming, the IWQWO is a potent detection of intrusion method. IWQWO makes sure that the IDS can successfully identify incursions in the IoT-based agricultural networks by choosing the most pertinent characteristics adjusting parameters for the model, and refining the categorizing models. Weight-based choice of characteristics and the quantum-enhanced optimization method offer more accuracy and effectiveness than conventional techniques, which makes them ideal for use in actual farming operations.

Algorithm of improved weighted quantum Whale Optimization with vision transformer for intrusion detection, atmospheric monitoring, and recommendation in smart agriculture

Inputs

  • Agricultural data (X): Includes environmental data (temperature, humidity), sensor inputs, images, etc.

  • Initial population (P): Set of candidate solutions representing feature subsets.

  • ViT model: For extracting features from image-based data (e.g., atmospheric conditions, crop images).

Outputs: Optimized decisions for intrusion detection, monitoring, and crop recommendations.

Step 1: Initialize population of Whale packs (IWQWO) Initialization)

Step 1.1 Initialize positions for each Whale \(\:{P}_{x}\:\)in the feature space: \(\:{P}_{x}=\left[{p}_{x1},{p}_{x2},\dots\:,{p}_{xm}\right]\:\)where \(\:{p}_{xy}\) is the position of the xth Whale in the yth feature dimension.

Step 1.2: Randomize weights for each Whale to explore solution space:

$$\:{w}_{x}=random\left(0,\:1\right)$$
(25)

Step 2: Quantum weight update (Quantum approach)

Update the position of each Whale using quantum-inspired principles:

$$\:{P}_{x}^{new}={P}_{x}+{w}_{x}\times\:({P}_{best}-{P}_{x})+Quantum\:perturbation\:term\:$$
(26)

\(\:{P}_{best}\) is the best solution found so far. Quantum perturbation term: Adds randomness inspired by quantum principles for better exploration.

Step 3: Recursive Fisher score calculation (RFSC) for feature selection

Step 3.1 Calculate Fisher Score for Each Feature using Eq. (12)

Step 3.2: Rank Features Based on Fisher Score: Sort features by their Fisher Score in descending order.

Step 3.3: Recursive Feature Elimination: Eliminate the least informative features by recursively removing features with the lowest Fisher Score.

$$\:{f}_{new}=\left\{{f}_{x}|FisherScore\left({f}_{y}\right)>threshold\right\}$$
(27)

Step 3.4: Iterative Optimization: Apply RFSC iteratively and update the feature set for the IWQW optimization process.

Step 4: Feature extraction using vision transformer (ViT)

Step 4.1: Preprocess Image Data (for ViT): Rescale input images X to a fixed size and apply augmentation:

$$\:{X}_{rescaled\:}=Rescale\left(X\right)\:$$
(28)

Step 4.2: Patch Embedding: Divide the image \(\:{X}_{rescaled\:}\) into small non-overlapping patches of size p x p and flatten them into vectors.

$$\:{Patch}_{x}=Flatten\left({X}_{rescaled\:}\right[x\left]\right)\:$$
(29)

Step 4.3: Self-Attention Mechanism: Apply multi-head self-attention to capture dependencies:

$$\:Q={IW}_{q},\:K={IW}_{k},\:V={IW}_{v}\:$$
(30)

Where Q, K, V are queries, keys, and values, and \(\:{W}_{q}\), \(\:{W}_{k}\), \(\:{W}_{v}\), are learned weight matrices.

Step 4.4: Feature Aggregation: Aggregate the attention output into a vector:

$$\:Features=Attention(Q,\:K,\:V)$$
(31)

Step 5. Fitness evaluation using IWQW optimization

Step 5.1: Fitness Function for IWQW: The fitness function evaluates how well each solution (Whale) performs across tasks such as intrusion detection, atmospheric monitoring, and crop recommendation:

$$\begin{aligned} \:Fitness\left( {P_{x} } \right) & = w_{{\text{int} rusion}} \times \:IntrusionLoss\left( {P_{x} } \right) + w_{{monitoring}} \\ & \times \:\:MonitoringLoss\left( {P_{x} } \right) + w_{{recommendation}} \times \:\text{Re} commendationLoss\left( {P_{x} } \right)\: \\ \end{aligned}$$
(32)

IntrusionLoss(\(\:{P}_{x}\)): Evaluates the performance of intrusion detection.

MonitoringLoss(\(\:{P}_{x}\)): Evaluates atmospheric condition monitoring.

Recommendationloss(\(\:{P}_{x}\)): Evaluates crop recommendation system performance.

Step 5.2: Selection of Best Solution: After evaluating the fitness of each Whale, the position of the best solution is selected:

$$\:{P}_{best}=arg\:max\left(Fitness\right({P}_{x}\left)\right)\:$$
(33)

Step 6: Feature selection and optimization

Step 6.1: Update Population with Selected Features: Use the selected feature subset from RFSC to update the Whale population:

$$\:{P}_{x}^{new}={P}_{x}+\alpha\:\times\:\left({P}_{best}-{P}_{x}\right)$$
(34)

Where \(\:\alpha\:\) is the learning rate.

Step 6.2: Convergence Criteria: The algorithm terminates when the fitness reaches a threshold or after a predefined number of iterations.

Step 7: Output the final recommendations

Step 7.1: Final Feature Set: After several iterations, the optimal feature subset is obtained.

Step 7.2: Prediction for Intrusion Detection: Intrusion detection decisions are made using the selected feature set.

Step 7.3: Atmospheric Monitoring: Monitor atmospheric conditions using the selected features.

Step 7.4: Final Crop Recommendations: Provide optimized crop recommendations based on the feature set.

Final output

  • Intrusion detection: Optimized predictions for security in smart agricultural environments.

  • Atmospheric monitoring: Real-time data on atmospheric conditions.

  • Crop recommendation: Optimized and personalized crop management recommendations.

By incorporating Recursive Fisher Score Calculation (RFSC) into the IWQWO - ViT framework, the algorithm can effectively select the most relevant features for complex tasks in Smart Agriculture. The IWQWO optimization ensures that the solution space is explored efficiently, while ViT enables advanced feature extraction from image-based data. This leads to optimized decisions for intrusion detection, atmospheric monitoring, and crop recommendation, enhancing overall performance in real-time agricultural systems.

Atmospheric monitoring explanation

To evaluate the surroundings and forecast changes, atmospheric surveillance entails tracking and evaluating a variety of natural characteristics such as humidity, temperature, stress, quality of the air, and other weather-related information. Determining how conditions outside affect crop development, production, and health is made easier by air surveillance in the context of innovative farming. These characteristics may be tracked in real-time and insightful information can be obtained by combining advanced techniques such as IWQWO- ViT.

Atmospheric monitoring model

Let’s define the key atmospheric parameters for the monitoring system as variables: T: Temperature; H: Humidity; P: Air pressure; AQI: Air Quality Index The goal is to monitor these parameters over time and optimize crop recommendations based on the changes in these parameters.

The fitness function used in IWQW optimization for atmospheric monitoring is a weighted sum of the losses or errors in predicting each of these atmospheric parameters. These losses reflect the difference between observed values and predicted values of each parameter. The fitness function is formulated as:

$$\:Fitness\left({P}_{x}\right)={w}_{T}.{Loss}_{T}\left({P}_{x}\right)+{w}_{H}.{Loss}_{H}\left({P}_{x}\right)+{w}_{P}.{Loss}_{P}\left({P}_{x}\right)+\:{w}_{AQI}.{Loss}_{AQI}\left({P}_{x}\right)\:$$
(35)

Where: \(\:{w}_{T}\), \(\:{w}_{H}\), \(\:{w}_{P}\), \(\:{w}_{AQI}\) are the weights associated with each parameter, representing their importance in the atmospheric monitoring task. \(\:{Loss}_{T}\left({P}_{x}\right)\), \(\:{Loss}_{H}\left({P}_{x}\right)\), \(\:{Loss}_{P}\left({P}_{x}\right)\), \(\:{Loss}_{AQI}\left({P}_{x}\right)\:\) are the loss functions (or errors) for temperature, humidity, air pressure, and air quality, respectively.

Loss function (Mean squared error)

Each loss function is computed as the mean squared error (MSE) between the observed and predicted values for each parameter:

$$\:{Loss}_{I}\left({P}_{x}\right)=\frac{1}{N}\sum\:_{y=1}^{N}{\left({I}_{obs.y}-{I}_{pred,y}\left({P}_{x}\right)\right)}^{2}$$
(36)

Where: \(\:{I}_{obs.y}\) is the observed value of parameter I (where I can be T, H, P, AQI) at time y. \(\:{I}_{pred,y}\left({P}_{x}\right)\) is the predicted value of parameter I at time y for the current Whale position \(\:{P}_{x}\). N is the total number of data points (samples) in the monitoring period.

Fitness calculation example for atmospheric monitoring

Monitoring temperature (T) and humidity (H), the fitness function becomes:

$$\:Fitness\left({P}_{x}\right)={w}_{T}.\left(\frac{1}{N}\sum\:_{y=1}^{N}{\left({T}_{obs.y}-{T}_{pred,y}\left({P}_{x}\right)\right)}^{2}\right)+{w}_{H}.\left(\frac{1}{N}\sum\:_{y=1}^{N}{\left({H}_{obs.y}-{H}_{pred,y}\left({P}_{x}\right)\right)}^{2}\right)$$
(37)

Atmospheric monitoring is essential for understanding the environmental conditions affecting agriculture. The equation above highlights the process of quantifying and optimizing the prediction of various atmospheric parameters using real-time data. By integrating IWQWO optimization and ViT agricultural systems can predict environmental changes and provide actionable insights to optimize crop growth, irrigation, and other farming practices, ensuring greater efficiency and sustainability in smart agriculture.

Results and discussions

Several essential elements are usually included in the experimental setup for the IWQWO with ViT method in the context of climate surveillance and intelligent farming. To collect environmental information from a variety of sensors, such as those measuring temperature, humidity, pressure in the atmosphere, and the condition of the air, data-collecting devices are first set up and put in agricultural settings. All of these sensors are connected to a central information processing unit, which records and processes information in real-time. The status of the crop field is then monitored by satellite or UAV images undergo additional processing using the ViT to obtain features from these visual inputs. The IWQWO-ViT method optimizes the method of decision-making by modifying the variables in response to the ongoing feedback loop that the observed data provides. The technique continuously refines the framework to enhance forecasts for environmental variables, and the measure of fitness is computed based on errors in the prediction of environmental variables. Using performance parameters like precision and rate of convergence monitored for the method’s efficacy in real-time atmosphere surveillance and agricultural making choices, the system would also provide an environment for simulation for testing different optimizing settings shown in Table 7.

Table 7 Parameter settings.
Fig. 8
Fig. 8The alternative text for this image may have been generated using AI.
Full size image

The outcome of sensor data.

Figure 8 shows the information from the first three fields: Soil moisture, Temperature and Humidity from sensors. The output of the temperature, relative humidity, and moisture sensors utilized to irrigate the initial information is shown in Fig. 8. Effective device activities throughout the feedback process period are shown in this continuous chart.

Fig. 9
Fig. 9The alternative text for this image may have been generated using AI.
Full size image

The loss and accuracy of proposed system.

Proposed model is considered well-fitted when its precision stabilizes and both validation and training losses plateau without significant divergence, indicating the absence of underfitting or overfitting. The relationship between precision and loss is examined as the epoch size varies. Figure 9a illustrates proposed model validation and training accuracy increase linearly before stabilizing after reaching a threshold. Similarly, Fig. 9b presents the training and validation losses showing minor differences between them. This suggests that the model is correctly fitted, ensuring optimal generalization without overfitting or underfitting.

Fig. 10
Fig. 10The alternative text for this image may have been generated using AI.
Full size image

Performance analysis of time complexity.

Figure 10 illustrates the time complexity analysis duration of the proposed and existing systems. The results show that CPU operation time and memory usage increase exponentially. The temporal complexity of AGRU remains lower compared to existing systems making it a more efficient choice for time-series analysis.

The Taylor Diagram is an innovative method for visualizing and comparing the performance of different models or predictions against a reference dataset (e.g., observed or actual data). It effectively condenses three key statistical measures into a single 2D plot shown in Fig. 11:

Correlation coefficient (Cosine of the angle)

Represents how well a model correlates with the reference data. Angle with the horizontal axis determines correlation strength.

Closer to 0° → Stronger correlation and better model performance.

Closer to 180° → Weaker or negative correlation, indicating poor performance.

Standard deviation (Distance from origin)

Measures the model’s average deviation from the reference dataset. Distance from the origin represents the magnitude of variation.

Closer to the Reference Point (Black Dot) → The model’s variation is similar to real data, which is desirable.

Farther from the Reference Point → Indicates either overestimation or underestimation of variability.

Root mean square deviation (RMSD)

The Euclidean distance between the model’s point and the reference data point (black dot). Lower RMSD means the prediction aligns more closely with the actual data, indicating better consistency.

By integrating these three statistical metrics, the Taylor Diagram provides a comprehensive and intuitive way to assess and compare model accuracy, making it a valuable tool for evaluating predictions in fields like climate science, machine learning, and environmental monitoring.

Fig. 11
Fig. 11The alternative text for this image may have been generated using AI.
Full size image

Taylor plots of prediction effects of different models on soil nutrient elements. (a) OM prediction effect; (b) N element prediction effect; (c) P element prediction effect; (d) K element prediction effect.

The Taylor Diagram provides a concise visual summary of model performance by illustrating the correlation, deviation from the mean, and Root Mean Square Deviation (RMSD). Understanding these metrics helps in evaluating how well different models replicate or predict real-world phenomena. A higher correlation indicates better agreement with actual data, while a deviation closer to the reference point suggests improved consistency. A lower RMSD reflects better predictive accuracy. When interpreting these diagrams, it is essential to consider the specific study context and dataset characteristics to ensure meaningful conclusions and optimal model selection.

Fig. 12
Fig. 12The alternative text for this image may have been generated using AI.
Full size image

Performance measures.

The proposed IWQW-ViT model outperforms existing systems in terms of accuracy, precision, recall, specificity, and F1-score. The accuracy of IWQW-ViT is significantly higher due to its enhanced feature selection and optimization capabilities, leading to improved intrusion detection and atmospheric monitoring shown in Fig. 12. The results indicate that IWQWO- ViT provides a more reliable and efficient approach for smart agriculture applications compared to the four existing systems.

Fig. 13
Fig. 13The alternative text for this image may have been generated using AI.
Full size image

Performance measures (different selected and fitness size).

The comparison of the IWQWO-ViT model with four existing systems Mogrifier RNN, Attention GRU, Transformer with Attention LSTM, and GRU demonstrates its superior performance in terms of average select size, best fitness, average size, average fitness, and selected size shown in Fig. 13. This highlights that the IWQWO-ViT model enhances the selection process and optimizes key parameters more effectively, leading to improved overall performance.

Fig. 14
Fig. 14The alternative text for this image may have been generated using AI.
Full size image

Performance measures (Error).

The performance comparison of the proposed IWQW-ViT model with four existing systems based on Mean Absolute Error (MAE), Mean Squared Error (MSE), and Root Mean Squared Error (RMSE) indicates that the proposed model achieves the lowest error values across all metrics. The IWQWO-ViT model achieves an MAE of 0.021, MSE of 0.004, and RMSE of 0.063, significantly outperforming the existing approaches shown in Fig. 14. Overall, the IWQW-ViT model’s lower error metrics demonstrate its superior learning capability, precise feature extraction, and effective optimization strategy, making it the most reliable approach among the compared models.

Table 8 Performance measures (Monitoring error, computational efficiency, intrusion detection rate and robustness).

The proposed IWQWO-ViT model achieves the lowest atmospheric monitoring error (0.021), indicating superior accuracy in monitoring atmospheric conditions shown in Table 8. It also exhibits high computational efficiency making it suitable for real-time applications. The intrusion detection rate (97.8%) is significantly higher than the existing models, demonstrating its effectiveness in detecting anomalies. In terms of robustness, the IWQWO-ViT model is the strongest, indicating its ability to maintain performance under varying conditions.

Table 9 Various crop recommendation using proposed system in various places in Tamil Nadu.

The IWQW-ViT System tailors the nutrient recommendations for various crops based on the soil types and specific nutrient requirements of each crop. For instance, in regions such as Thanjavur, Cuddalore, and Tiruvarur where rice is predominantly grown, the system recommends fertilizers based on clayey soil and provides a balanced mix of nitrogen, phosphorus, and potassium. Similarly, crops such as sugarcane, cotton, groundnut, tomato, chili, and banana are recommended for specific nutrient dosages depending on soil type and environmental conditions in other regions of Tamil Nadu. The system uses real-time atmospheric and soil data to optimize fertilizer recommendations, ultimately improving crop yield and resource utilization efficiency. The nutrient recommendations are designed to enhance agricultural productivity while minimizing wastage and environmental impact shown in Table 9.

Fig. 15
Fig. 15The alternative text for this image may have been generated using AI.
Full size image

Performance measures of recommendation accuracy.

The Proposed IWQWO-ViT system achieves the highest recommendation accuracy at 95.3% for advanced feature extraction and optimization. This system excels in providing accurate nutrient recommendations based on atmospheric data and soil conditions. Existing systems show relatively good performance, with GRU showing the lowest accuracy of 85.1%. These systems are generally less effective than the proposed approach in leveraging quantum optimization and vision-based feature extraction techniques for precise nutrient recommendations shown in Fig. 15. Comparison of training and validation accuracy and loss of proposed and existing systems shown in Fig. 16.

Fig. 16
Fig. 16The alternative text for this image may have been generated using AI.
Full size image

Comparison of training and validation accuracy and loss of proposed and existing systems.

Conclusions

The proposed IWQWO-ViT framework enhances intrusion detection, atmospheric monitoring, and recommendation systems in smart agriculture by addressing key challenges such as energy inefficiency, network instability, and inaccurate anomaly detection in WSN-based farming. By integrating quantum-inspired optimization techniques with adaptive weighting modifications, IWQWO improves node clustering, route optimization, and anomaly identification, ensuring efficient energy consumption and system longevity. The ViT enhances high-precision environmental surveillance by leveraging spatial-temporal relationships in sensor data, reducing false alarms, and enabling real-time intrusion detection. Extensive modeling and evaluations demonstrate significant improvements in energy efficiency, network reliability, and detection accuracy compared to existing approaches. This hybrid framework fosters intelligent decision-making, enhances security, and optimizes sensor data analysis, making it a robust, scalable, and resource-efficient solution for next-generation smart farming. By combining cutting-edge artificial intelligence with bio-inspired optimization, IWQWO-ViT ensures improved sustainability, operational efficiency, and environmental resilience in precision agriculture.