0% found this document useful (0 votes)
15 views

CONTENT 1

Uploaded by

nanthakumarbee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

CONTENT 1

Uploaded by

nanthakumarbee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

CHAPTER 1

INTRODUCTION

1.1 PRECISION AGRICULTURE

Precision agriculture (PA) is a farming management strategy based on


observing, measuring and responding to temporal and spatial variability to improve
agricultural production sustainability.[2] It is used in both crop and livestock
production. Precision agriculture often employs technologies to automate agricultural
operations, improving their diagnosis, decision-making or performing.[3][4] First
conceptual work on PA and practical applications go back in the late 1980s.[5] The goal
of precision agriculture research is to define a decision support system (DSS) for whole
farm management with the goal of optimizing returns on inputs while preserving
resources.

Among these many approaches is a phytogeomorphological approach which ties


multi-year crop growth stability/characteristics to topological terrain attributes. The
interest in the phytogeomorphological approach stems from the fact that
the geomorphology component typically dictates the hydrology of the farm field.

The practice of precision agriculture has been enabled by the advent


of GPS and GNSS. The farmer's and/or researcher's ability to locate their precise
position in a field allows for the creation of maps of the spatial variability of as many
variables as can be measured (e.g. crop yield, terrain features/topography, organic
matter content, moisture levels, nitrogen levels, pH, EC, Mg, K, and
others).[10] Similar data is collected by sensor arrays mounted on GPS-
equipped combine harvesters. These arrays consist of real-time sensors that measure
everything from chlorophyll levels to plant water status, along
with multispectral imagery.[11] This data is used in conjunction with satellite
imagery by variable rate technology (VRT) including seeders, sprayers, etc. to
1
optimally distribute resources. However, recent technological advances have enabled
the use of real-time sensors directly in soil, which can wirelessly transmit data without
the need of human presence.[12][13]

Precision agriculture has also been enabled by unmanned aerial vehicles that are
relatively inexpensive and can be operated by novice pilots. These agricultural
drones can be equipped with multispectral or RGB cameras to capture many images of
a field that can be stitched together using photogrammetric methods to create ortho
photos. These multispectral images contain multiple values per pixel in addition to the
traditional red, green blue values such as near infrared and red-edge spectrum values
used to process and analyze vegetative indexes such as NDVI maps.[14] These drones
are capable of capturing imagery and providing additional geographical references such
as elevation, which allows software to perform map algebra functions to build precise
topography maps. These topographic maps can be used to correlate crop health with
topography, the results of which can be used to optimize crop inputs such as water,
fertilizer or chemicals such as herbicides and growth regulators through variable rate
applications.

1.2 HISTORY

Precision agriculture is a key component of the third wave of


modern agricultural revolutions. The first agricultural revolution was the increase
of mechanized agriculture, from 1900 to 1930. Each farmer produced enough food to
feed about 26 people during this time.[15] The 1960s prompted the Green
Revolution with new methods of genetic modification, which led to each farmer
feeding about 156 people.[15] It is expected that by 2050, the global population will
reach about 9.6 billion, and food production must effectively double from current levels
in order to feed every mouth. With new technological advancements in the agricultural
revolution of precision farming, each farmer will be able to feed 265 people on the
same acreage.
2
1.2.1 OVERVIEW

The first wave of the precision agricultural revolution came in the forms of
satellite and aerial imagery, weather prediction, variable rate fertilizer application, and
crop health indicators. The second wave aggregates the machine data for even more
precise planting, topographical mapping, and soil data.

Precision agriculture aims to optimize field-level management with regard to:

Crop science: by matching farming practices more closely to crop needs (e.g. fertilizer
inputs);

Environmental protection: by reducing environmental risks and footprint of farming


(e.g. limiting leaching of nitrogen);

Economics: by boosting competitiveness through more efficient practices (e.g.


improved management of fertilizer usage and other inputs).

Precision agriculture also provides farmers with a wealth of information to:

 Build up a record of their farm


 Improve decision-making
 Foster greater traceability
 Enhance marketing of farm products
 Improve lease arrangements and relationship with landlords
 Enhance the inherent quality of farm products (e.g. protein level in bread-flour
wheat)

1.2.2 PRESCRIPTIVE PLANTING

Prescriptive planting is a type of farming system that delivers data-driven


planting advice that can determine variable planting rates to accommodate varying
conditions across a single field, in order to maximize yield. It has been described as

3
"Big Data on the farm." Monsanto, DuPont and others are launching this technology in
the US.

1.2.3 PRINCIPLES

Precision agriculture uses many tools but here are some of the basics: tractors,
combines, sprayers, planters, diggers, which are all considered auto-guidance systems.
The small devices on the equipment that uses GIS (geographic information system) are
what make precision agriculture what it is. You can think of the GIS system as the
“brain.” To be able to use precision agriculture the equipment needs to be wired with
the right technology and data systems. More tools include Variable rate technology
(VRT), Global positioning system and Geographical information system, Grid
sampling, and remote sensors

1.2.4 GEO LOCATING

Geo locating a field enables the farmer to overlay information gathered from
analysis of soils and residual nitrogen, and information on previous crops and soil
resistivity. Geo location is done in two ways

The field is delineated using an in-vehicle GPS receiver as the farmer drives a
tractor around the field.

The field is delineated on a base map derived from aerial or satellite imagery.
The base images must have the right level of resolution and geometric quality to ensure
that geo location is sufficiently accurate.

1.2.5 VARIABLES

Intra and inter-field variability may result from a number of factors. These
include climatic conditions (hail, drought, rain, etc.), soils (texture, depth, nitrogen
levels), cropping practices (no-till farming), weeds and disease. Permanent indicators—
chiefly soil indicators—provide farmers with information about the main
4
environmental constants. Point indicators allow them to track a crop's status, i.e., to see
whether diseases are developing, if the crop is suffering from water stress, nitrogen
stress, or lodging, whether it has been damaged by ice and so on. This information may
come from weather stations and other sensors (soil electrical resistivity, detection with
the naked eye, satellite imagery, etc.). Soil resistivity measurements combined with soil
analysis make it possible to measure moisture content. Soil resistivity is also a
relatively simple and cheap measurement

1.2.6 IMPLEMENTING PRACTICES

New information and communication technologies make field level crop


management more operational and easier to achieve for farmers. Application of crop
management decisions calls for agricultural equipment that supports variable-rate
technology (VRT), for example varying seed density along with variable-rate
application (VRA) of nitrogen and phytosanitary products.

 Precision agriculture uses technology on agricultural equipment (e.g. tractors,


sprayers, harvesters, etc.)
 Ppositioning system (e.g. GPS receivers that use satellite signals to precisely
determine a position on the globe)
 Geographic information systems (GIS), i.e., software that makes sense of all the
available data.
 Variable-rate farming equipment (seeder, spreader).

The economic and environmental benefits of precision agriculture have also


been confirmed in China, but China is lagging behind countries such as Europe and the
United States because the Chinese agricultural system is characterized by small-scale
family-run farms, which makes the adoption rate of precision agriculture lower than
other countries. Therefore, China is trying to better introduce precision agriculture

5
technology into its own country and reduce some risks, paving the way for China's
technology to develop precision agriculture in the future
1.3 ECONOMIC AND ENVIRONMENTAL IMPACTS
Precision agriculture, as the name implies, means application of precise and
correct amount of inputs like water, fertilizer, pesticides etc. at the correct time to the
crop for increasing its productivity and maximizing its yields. Precision agriculture
management practices can significantly reduce the amount of nutrient and other crop
inputs used while boosting yields.[40] Farmers thus obtain a return on their investment
by saving on water, pesticide, and fertilizer costs.

The second, larger-scale benefit of targeting inputs concerns environmental


impacts. Applying the right amount of chemicals in the right place and at the right time
benefits crops, soils and groundwater, and thus the entire crop cycle. Consequently,
precision agriculture has become a cornerstone of sustainable agriculture, since it
respects crops, soils and farmers. Sustainable agriculture seeks to assure a continued
supply of food within the ecological, economic and social limits required to sustain
production in the long term.

A 2013 article tried to show that precision agriculture can help farmers in
developing countries like India. Precision agriculture reduces the pressure by the
agriculture on the environment by increasing the efficiency of machinery and putting it
into use. For example, the use of remote management devices such as GPS reduces fuel
consumption for agriculture, while variable rate application of nutrients or pesticides
can potentially reduce the use of these inputs, thereby saving costs and reducing
harmful runoff into the waterways.

1.3.1 EMERGING TECHNOLOGIES


Precision agriculture is an application of breakthrough digital farming
technologies. Over $4.6 billion has been invested in agriculture tech companies—
sometimes called agtech.
6
1.3.2 ROBOTS

Self-steering tractors have existed for some time now, as John Deere equipment
works like a plane on autopilot. The tractor does most of the work, with the farmer
stepping in for emergencies. Technology is advancing towards driverless machinery
programmed by GPS to spread fertilizer or plow land. Autonomy of technology is
driven by the demanding need of diagnoses, often difficult to accomplish solely by
hands-on farmer-operated machinery. In many instances of high rates of production,
manual adjustments cannot sustain.[44] Other innovations include, partly solar
powered, machines/robots that identify weeds and precisely kill them with a dose of a
herbicide or lasers.

Agricultural robots, also known as AgBots, already exist, but advanced


harvesting robots are being developed to identify ripe fruits, adjust to their shape and
size, and carefully pluck them from branches.

1.3.3 DRONES AND SATELLITE IMAGERY

Drone and satellite technology are used in precision farming. This often occurs
when drones take high quality images while satellites capture the bigger picture. Aerial
photography from light aircraft can be combined with data from satellite records to
predict future yields based on the current level of field biomass. Aggregated images can
create contour maps to track where water flows, determine variable-rate seeding, and
create yield maps of areas that were more or less productive. Super
resolution enhancement methods are seeing increased use in crop disease
surveillance from low flying aircraft. Klapp et al. 2021 demonstrates a significantly
improved infrared super-resolution method using a convolution neural network

1.4 THE INTERNET OF THINGS

The Internet of things is the network of physical objects outfitted with


electronics that enable data collection and aggregation. IoT comes into play with the
7
development of sensors and farm-management software. For example, farmers can
spectroscopic ally measure nitrogen, phosphorus, and potassium in liquid manure,
which is notoriously inconsistent. They can then scan the ground to see where cows
have already urinated and apply fertilizer to only the spots that need it. This cuts
fertilizer use by up to 30%. Moisture sensors in the soil determine the best times to
remotely water plants. The irrigation systems can be programmed to switch which side
of tree trunk they water based on the plant's need and rainfall.

Innovations are not just limited to plants they can be used for the welfare of
animals. Cattle can be outfitted with internal sensors to keep track of stomach acidity
and digestive problems. External sensors track movement patterns to determine the
cow's health and fitness, sense physical injuries, and identify the optimal times for
breeding.

1.4.1 SMARTPHONE APPLICATIONS

Fig 1.1 Smart phone-integrated precision agriculture system

Smart phone and tablet applications are becoming increasingly popular in


precision agriculture. Smart phones come with many useful applications already
installed, including the camera, microphone, GPS, and accelerometer. There are also
applications made dedicated to various agriculture applications such as field mapping,
tracking animals, obtaining weather and crop information, and more. They are easily
portable, affordable, and have high computing power.

8
1.4.2 MACHINE LEARNING

Machine learning is commonly used in conjunction with drones, robots, and


internet of things devices. It allows for the input of data from each of these sources.
The computer then processes this information and sends the appropriate actions back to
these devices. This allows for robots to deliver the perfect amount of fertilizer or for
IoT devices to provide the perfect quantity of water directly to the soil. Machine
learning may also provide predictions to farmers at the point of need, such as the
contents of plant-available nitrogen in soil, to guide fertilization planning. As more
agriculture becomes ever more digital, machine learning will underpin efficient and
precise farming with less manual labour.

1.4.2.1 LEAF DISEASE DETECTION IN AGRICULTURE

A product quality control is fundamentally required in order to gain more value


added products [2]. Many studies show that quality of agricultural products can be
reduced from many causes. One of the most important factors of such quality is plant
diseases. Consequently, minimizing plant diseases allows substantially improving
quality of the products. Rice known as Oryza Sativa (specific name), is one of the most
utilized food plants and widely grown originated in ASIA. [4] Rice is an important crop
worldwide and over half of the world population relies on it for food. Many people in
the world including Malaysia eat rice as staple food. However, there are many factors
that make paddy rice production become slow and less productive. One of the main
factors is paddy disease. An abnormal condition that injures the plant or leads it to
function improperly is called as a disease. Diseases are readily recognized by their
symptoms. There are a lot of paddy disease types which are Bakanae, red disease virus,
brown spot disease and many more.[1] Image processing and computer vision
technology are very beneficial to the agricultural industry. They are more potential and
more important to many areas in agricultural technology [1]. Paddy Disease Detection
System is one of the very beneficial systems. It can help the paddy farmer detect the
9
disease faster. This study aims to develop a prototype system to automatically detect
and classify the paddy diseases by using image processing technique as an alternative
or supplemental to the traditional manual method.

10
CHAPTER 2

LITERATURE REVIEW

Automatic irrigation system using soil moisture sensor and temperature sensor
with microcontroller AT89S52
Srilikhitha ; M. Manoj Saikumar ; Nannu Rajan automates the irrigation
process thereby reducing the manual intervention and the water losses. It is more
helpful in the places where water scarcity is seen more. It consists of 2 sensors which
takes the values of temperature of surroundings and moisture level of soil. Output of
these sensors are given to ADC and then to microcontroller. Microcontroller compares
the values with the threshold values and drives the relay which controls the motor. LCD
display is used to display data in the field. GSM modem is also a part of design which
helps in transmitting SMS to farmer's phone number which contains the status of motor
in field. The design is cost effective and also affordable.

Smart farming—A prototype for field monitoring and automation in agriculture


K. Sreeram ; R. Suresh Kumar ;provides a solution for these problems by
helping farmer monitor and control various activities through his mobile via GSM and
DTMF technology in which data is transmitted from various sensors placed in the
agricultural field to the controller and the status of the agricultural parameters are
notified to the farmer using which he can take decisions accordingly. The main
advantage of this system is that it is semi-automated i.e. the decision is made by the
farmer instead of fully automated decision that results in precision agriculture. It also
overcomes the existing traditional practices that require high money investment,
energy, labour and time.
Application of wireless technologies in agricultural pumps
Deepali Kothari ; Arun Parakh attempt to implement automation for control of
electrical motor or pump used in agriculture domain. The agriculture work by its nature
is a field job, hence devices used are sparsely distributed. This makes it difficult for
11
farmers to control and operate these devices in real time. With the emerging
technologies, we have seen the advent of many wireless communication techniques,
having lower operating cost along with interactive protocols. The system's operational
range is scaled up by the use of the GSM communication system. This work suggested
a method which utilizes the potential of low power, high speed microcontrollers by
using widely accepted open source Android platform. The proposed model enables us
to control the field devices over a wireless link which is GSM based and can read
signals from sensors connected in the field and can send the sensed electrical
parameters of the motor or pump to an Android device. A GUI (Graphical User
Interface) is developed for Android device and successfully performed testing for
switching ON and OFF of the motor or pump remotely. Also, provided a simple display
of availability of power at remote locations.

Remote monitoring and control for liquid fertilizer and water irrigation
M. O. Sharma ; P. M. Sonwane propose android based agricultural support
system, that is, automatic irrigation system which adjusts the quantity of water based
on sensor data. Monitoring and control of water irrigation and level detector with liquid
fertilizer is being proposed in dissertation work with different control schemes and
monitoring methods implemented using the micro-controller 89S52 and PIC 18F4550.

Smart agro system using wireless sensor networks


A. Ruby Roselin ; A. Jawahar proposed project is to making agriculture smart
using IoT technologies. The important feature of this project includes the prevention of
crops from spoilage during rain and efficiently recycling the rain water for irrigation.
Secondly, it includes intruder alarm/buzzer which is used to detect any human/animal
intruder into the farm. Finally, the operation will be performed by interfacing Wi-Fi
module, GSM module and sensors with Arduino. With the proposed work, current
problems related to farming are solved by reducing human efforts, wastage of water
and updating the farmer about the live condition of the field on the mobile device
12
GSM based solar automatic irrigation system using moisture, temperature and
humidity sensors
Ateeq Ur Rehman ; Rao Muhammad Asif et al proposed design also has the
feature of GSM which makes this system wireless. The electricity required by
components is provided through solar panels hence this liberates us from interrupted
power supply due to load shedding. The water content is constantly judged and
whenever moisture level of soil gets low, the system sends a signal to motors asking
them to turn on. The motors automatically stop after soil reaches its maximum upper
threshold value which is decided by user. Every time the motor starts or stops
automatically, the user will get a SMS about the status of operation. The major
advantages of the project include avoidance from water wastage, growth of plants to
their maximum potential, less chances of error due to less labor and uninterrupted
supply of water due to solar energy.

Smart drip irrigation system for sustainable agriculture


G Kavianand ; V M Nivas presents a fully automated drip irrigation system
which is controlled and monitored by using ARM9 processor. PH content and the
nitrogen content of the soil are frequently monitored. For the purpose of monitoring
and controlling, GSM module is implemented. The system informs user about any
abnormal conditions like less moisture content and temperature rise, even concentration
of CO2 via SMS through the GSM module.

Wireless sensor based control system in agriculture field


K. S. Vijula Grace ; Silja Kharim ; P. Sivasakthi proposed work describes the
automated system to make effective utilization of water resources for agriculture and
crop growth monitoring using GSM. The effective utilization of drip irrigation process
is improved by using the signals obtained from soil moisture sensor. The output signals
of the sensors are coordinated by the microcontroller and transmitted to the user with
the help of GSM Modem. Irrigation is the process of artificially supplying water to land
13
where crops are cultivated. Traditionally hand pumps; canal water and rainfall were a
major source of water supply for irrigation. This method has led to severe drawbacks
like under irrigation, over-irrigation which in turn causes leaching and loss of nutrient
content of soil. The optimized water use for an agriculture crops has been achieved
successfully by this system. The system that can report data to the cultivator remotely
and allows to control the process effectively with GSM.

Certain investigation of precision agriculture robot using lab view


Ashok Jhunjhunwala ; Jayalakshmi Umadikar ; Suma Prashant presents a new
approach to building an Agricultural Advisory System aimed at bridging the
information gaps that exist between farmers and extension workers and agricultural
scientists in a country like India. It demonstrates the power of two-way mobile phones
today, which when combined with innovative methods could provide services to
farmers that could not even be envisaged till yesterday. The customized and
personalized advisory becomes especially important in the Indian context, where 52%
of the population depends on agriculture but generates merely 13.9% of its Gross
Domestic Product (GDP). With fragmented landholdings, the number of independent
farmers has risen to 88 million with near-stagnant productivity. Growth-acceleration is
possible only with customized advisory. India currently has a 900 million strong mobile
phone subscriber base largely operating over voice oriented 2G GSM (Global System
for Mobile Communications) and GPRS (General Packet Radio Service) networks.
With ever increasing rural mobile penetration, personalized agricultural advisory is a
distinct possibility. The paper presents an innovative technology development effort,
analyses the technological challenges faced as well as discusses the feedback obtained
from early field implementation and focuses on what needs to be done in future to scale
such systems.

14
CHAPTER 3

METHODOLOGY

3.1 EXISTING SYSTEM

3.1.1 METHODOLOGIES USED FOR INVESTIGATION

This chapter looks into the various methodologies found in literature review.
Different researchers investigated in the area of smart irrigation practices in different
levels, including smart sprinklers, soil sensors, and automatic timer with rain sensor.
Therefore, different methods were studied profoundly to finally choose the best
approach that suits the location of Dubai, the time boundary of this research study and
the available resources. Following are the different methods and approaches used by
different scholars in investigating the area of smart landscape practices and smart
irrigation systems.

 Field Experiment
 Survey and Data Collection
 Modeling approach

Field Experiment

This is the most common approach used by many researchers investigating the
area of irrigation practices and smart landscaping. This method enabled the researchers
to obtain valid results while observing the changes on plantation growth and water
efficiency on real field experiment. Usually, the results obtained are combined with
another method, for instance analytical analysis and calculation to indicate the
measurement and transform the data into tables and graphs. Various factors should be
taken into consideration when doing field experiment such as weather condition,
factors affecting vegetation growth, soil condition and etc

15
Survey and Data Collection

Survey and Data Collection Surveys are usually used when measuring large
sample of population’s opinion. Surveys may include various questionnaire and
interviews and is important to understand public’s point of view and essential for
research field of study. Various researchers investigated the need for smart irrigation
practices through field survey. Cremades, Wang, and Morris (2015) conducted a survey
to measure the impact of policy makers in promoting modern irrigation practices in
China and the policies that intervene the use of these technologies. The survey was
carried out in 7 different provinces and grouped into 3 groups: Traditional, household
and community. The objective of this survey was to measure the current incentives put
towards adapting modern irrigation technologies and to measure the subsidies and
polices that intervene towards promoting irrigation technologies.

Modelling approach this method can be really useful when changing variables
constantly in a research study. It is less costly yet can be time consuming. The
percentage of error is very limited due to the accuracy of applications used. In research
studies such as this, very few used this approach in measuring the intelligent aspect of
landscape and agriculture.

Mixed approach

This method includes combining two methods from the previous approaches.
Many found to use mix-method approach when measuring various parameters
especially when combining qualitative and quantitative data. In the study of this area,
many tend to use this approach to facilitate their measurements and data obtained.
Especially after Paris agreement COP21 many countries looked into various
contributions that will lessen the negative impact. The author used combination
approach called CSA-RA which is a combination of rapid rural appraisal (RRA) and
participatory rural appraisal (PRA). For rapid information, RRA approach is used to

16
extract the knowledge from farmers and experts. RRA extract information related to
household, economic resources, social information related to education, the size of the
household and farm characteristics. When looking into approaches that engage
community members through various participatory exercises, CSA utilize PRA
approach. PRA empower stakeholders to evaluate their thoughts on various problems
such as the impact of climate change or agriculture, agriculture management systems,
the availability of natural resources.
3.1.2 MANUAL SCHEDULING
Controllers The manual scheduling controllers use an open loop control system.
This allows the user to define the start and stop time of the irrigation as well as the
irrigation periodicity. This type of controllers has no feedback loop, and so is very
inefficient. Periods of time are defined by the user and do not take into account the
climate changes which the soil and the plants are subject to

Fig 3.1 Open Loop Controller

Smart Scheduling Controllers a Southern California report identified two major


smart irrigation systems: weather based systems and soil moisture based systems.
These type of controllers use a close loop control system (see Figure), which means
that feedback is received from the irrigated system and the irrigation is scheduled
according to information related to site conditions such as soil moisture.

Fig 3.2 Close Loop Controller


17
Weather-based Irrigation Controllers Weather based irrigation controllers are
also known as ET (evapo transpiration) controllers. Irrigation based in ET requirements
is a quantitative method, which is defined as the sum of evaporation and plant
transpiration, calculated as a function of a set of parameters based on weather
conditions (radiation, air temperature, humidity and wind speed). These parameters
used to calculate plants evapo transpiration may be collected in two different ways.
Either having an on site weather station, or using weather station data from a remote
weather station. The irrigation schedule is fulfilled calculating daily ET. Although this
method is more efficient than the manual controlled system, it is not the most efficient
one, since the same amount of water is applied at different areas, without worrying
about the soil variations, plant type or the distinct microclimates

Comparison between Smart Irrigation Controllers a comparative study has been


performed in order to compare the irrigation efficiency using an weather-based
controller and an on-demand soil moisture-based controller. The results observed in this
comparison were very conclusive. It was concluded that a soil moisture-based irrigation
system is more efficient, offering water savings of almost 50% compared to the ET-
based controller.

3.2 PROPOSED SYSTEM

In this work, this problem is solved by proposing a recommendation system


through machine learning model to recommend a crop for the site specific parameters
with high accuracy and efficiency. Different sensors that measure the environmental
parameters according to the plant requirement are used for controlling the environment.
Then, a cloud server creates for remotely accessing the system when it connects using
IoT.

Suitable crop is also being advised to the farmers according to the parameters. A
platform to buy and sell products online will help the farmers grow in an increasingly

18
digital world. A discussion forum has also been added so that farmers can have their
questions answered by the agricultural experts. This paper aims to ease the life of the
farmers.

In this work, for the classification of suitable crop, Deep Neural Networks
(DNN) is proposed .The main goal is to classify data in terms of higher accuracy

Fig 3.3 Proposed work flow

Modules

• Data Preparation
• Feature extraction
• Deep Dense ANN model building
• Performance analysis

19
3.2.1 DEEP DENSE ARTIFICIAL NEURAL NETWORK

Artificial Neural Networks are the most popular machine learning


algorithms today. The invention of these Neural Networks took place in the 1970s but
they have achieved huge popularity due to the recent increase in computation power
because of which they are now virtually everywhere. In every application that you use,
Neural Networks power the intelligent interface that keeps you engaged.

Fig 3.4 ANN model

What is ANN?

Artificial Neural Networks are a special type of machine learning algorithms


that are modeled after the human brain. That is, just like how the neurons in our
nervous system are able to learn from the past data, similarly, the ANN is able to learn
from the data and provide responses in the form of predictions or classifications.

ANNs are nonlinear statistical models which display a complex relationship


between the inputs and outputs to discover a new pattern. A variety of tasks such as
image recognition, speech recognition, machine translation as well as medical
diagnosis makes use of these artificial neural networks.

20
An important advantage of ANN is the fact that it learns from the example data
sets. Most commonly usage of ANN is that of a random function approximation. With
these types of tools, one can have a cost-effective method of arriving at the solutions
that define the distribution. ANN is also capable of taking sample data rather than the
entire dataset to provide the output result. With ANNs, one can enhance existing data
analysis techniques owing to their advanced predictive capabilities.

A deep dense artificial neural network (ANN) is a type of deep learning model
that consists of multiple layers of densely connected neurons. It is also commonly
referred to as a fully connected neural network or a feed forward neural network.

In a deep dense ANN, each neuron in a layer is connected to every neuron in the
previous and subsequent layers, forming adense or fully connected network
architecture. This means that each neuron in a layer receives input from all neurons in
the previous layer and sends output to all neurons in the subsequent layer. This allows
for complex and non-linear transformations of input data as it passes through the
network.

Deep dense ANNs are called "deep" because they typically have multiple hidden
layers between the input and output layers. These hidden layers allow the network to
learn increasingly abstract representations of the input data, capturing higher-level
features or patterns. The depth of the network refers to the number of hidden layers in
the network.

Deep dense ANNs are used for a wide range of machine learning tasks,
including image and speech recognition, natural language processing, and many other
applications. They are known for their ability to learn complex patterns and
representations from large amounts of data, and they have achieved state-of-the-art
performance in many areas of machine learning and artificial intelligence.

21
3.2.2 ARTIFICIAL NEURAL NETWORKS ARCHITECTURE

The functioning of the Artificial Neural Networks is similar to the way neurons
work in our nervous system. The Neural Networks go back to the
early 1970s when Warren S McCulloch and Walter Pitts coined this term. In order to
understand the workings of ANNs, let us first understand how it is structured. In a
neural network, there are three essential layers.

Input Layers

The input layer is the first layer of an ANN that receives the input information in the
form of various texts, numbers, audio files, image pixels, etc.

Hidden Layers

In the middle of the ANN model are the hidden layers. There can be a single hidden
layer, as in the case of a perception or multiple hidden layers. These hidden layers
perform various types of mathematical computation on the input data and recognize the
patterns that are part of.

Output Layer

In the output layer, we obtain the result that we obtain through rigorous computations
performed by the middle layer.

In a neural network, there are multiple parameters and hyper parameters that
affect the performance of the model. The output of ANNs is mostly dependent on these
parameters. Some of these parameters are weights, biases, learning rate, batch size etc.
Each node in the ANN has some weight.

Each node in the network has some weights assigned to it. A transfer function is
used for calculating the weighted sum of the inputs and the bias.

22
Fig 3.5 Neuron layer processing

After the transfer function has calculated the sum, the activation function obtains
the result. Based on the output received, the activation functions fire the appropriate
result from the node. For example, if the output received is above 0.5, the activation
function fires a 1 otherwise it remains 0.

Some of the popular activation functions used in Artificial Neural Networks is


Sigmoid, RELU, Soft max, tanh etc.

Fig 3.6 Soft max working

Based on the value that the node has fired, we obtain the final output. Then,
using the error functions, we calculate the discrepancies between the predicted output

23
and resulting output and adjust the weights of the neural network through a process
known as back propagation.

ANNs are part of an emerging area in Machine Learning known as Deep


Learning. Many people are confused between Deep Learning and Machine Learning.
Are you among one of them? Check this easy to understand article on Deep Learning
vs Machine Learning.

3.2.3 BACK PROPAGATION IN ARTIFICIAL NEURAL NETWORKS

In order to train a neural network, we provide it with examples of input-output


mappings. Finally, when the neural network completes the training, we test the neural
network where we do not provide it with these mappings. The neural network predicts
the output and we evaluate how correct the output is using the various error functions.
Finally, based on the result, the model adjusts the weights of the neural networks to
optimize the network following gradient descent through the chain rule.

3.2.4 TYPES OF ARTIFICIAL NEURAL NETWORKS

There are two important types of Artificial Neural Networks.

 Feed Forward Neural Network


 Feed Back Neural Network
 Feed Forward Artificial Neural Networks

In the feed forward ANNs, the flow of information takes place only in one
direction. That is, the flow of information is from the input layer to the hidden layer
and finally to the output. There are no feedback loops present in this neural network.
These type of neural networks are mostly used in supervised learning for instances such
as classification, image recognition etc. We use them in cases where the data is not
sequential in nature.

24
Fig 3.7 Layer processing

3.2.5 FEEDBACK ARTIFICIAL NEURAL NETWORKS

In the feedback ANNs, the feedback loops are a part of it. Such type of neural
networks are mainly for memory retention such as in the case of recurrent neural
networks. These types of networks are most suited for areas where the data is
sequential or time-dependent.

Deep Echo State Networks (DeepESN) represent a powerful advancement in the


field of recurrent neural networks (RNNs) and machine learning. They are a type of
reservoir computing model that has gained attention for their ability to efficiently
handle complex temporal data while mitigating some of the challenges associated with
training traditional deep RNNs. DeepESN is an extension of the original Echo State
Network (ESN) concept, incorporating multiple hidden layers to enable the learning of
hierarchical features from sequential data.

3.2.5.1 ARCHITECTURE

At its core, the architecture of DeepESN consists of three main components:


input layers, reservoir layers, and output layers. Here's a breakdown of each
component.

25
Input Layers

These layers receive the input data, which can be sequential or time-series data.
Input nodes are connected to the reservoir nodes, forming a set of weighted connections
that convey information to the reservoir.

Spe Neuronal reservoir


ctru
m
hist
oric
al
dat
a

Outputs

Activation function

Fig 3.8 ESN architecture

Reservoir Layers
The reservoir layers are a crucial aspect of DeepESN's architecture. They
comprise a large number of recurrently connected nodes, often referred to as neurons or
units. These nodes are interconnected with fixed random weights, forming a "reservoir"
that captures temporal dependencies and complex patterns present in the input data.
DeepESN extends the original ESN concept by introducing multiple hidden reservoir
layers stacked on top of each other. Each hidden layer captures progressively more
abstract and complex features from the input data.
Output Layers
The output layers generate predictions or classifications based on the
information processed through the reservoir layers. These layers can vary in complexity
and can involve linear or nonlinear transformations of the reservoir states. The output

26
can be a direct prediction of the next time-step's value or a higher-level representation
used for various tasks.
3.2.5.2 WORKING PRINCIPLE
DeepESNs operate in a two-step process: the initialization phase and the training
phase.
Initialization Phase
During this phase, the reservoir's recurrent weights are randomly generated and
fixed. This randomness helps the reservoir capture a diverse range of temporal patterns.
The input data is then propagated through the input nodes and reservoir layers, and the
reservoir states are collected for the entire input sequence without any learning or
adjustment of the weights.
Training Phase
In this phase, the collected reservoir states from the initialization phase are used
as inputs to train the output layers. This training phase involves learning the output
weights through methods like linear regression or gradient-based optimization. The
training process adjusts the output weights to minimize the difference between the
predicted output and the desired target output.
Advantages
Deep Echo State Networks offer several advantages:
1. Memory and Efficiency: The reservoir's fixed random weights enable efficient
training, as the training is focused on adjusting only the output weights. This reduces
the risk of over fitting and speeds up the training process.
2. Hierarchical Representation: The incorporation of multiple hidden layers allows
DeepESNs to capture hierarchical features and abstract representations from the input
data.
3. Complex Temporal Patterns: DeepESNs excel at capturing complex temporal
dependencies, making them suitable for tasks involving sequential or time-series data.

27
CHAPTER 4

SOFTWARE SPECIFICATION

4.1 SOFTWARE REQUIRED

 IDLE 1.7
 PYTHON 1.7.6
4.2 HARDWARE REQUIRED
 System : Windows Xp Professional Service Pack 2
 Processor : Up to 1.5 GHz
 Memory : Up to 512 MB RAM
4.3 PYTHON
The Python language had a humble beginning in the late 1980s when a
Dutchman Guido Von Rossum started working on a fun project, which would be a
successor to ABC language with better exception handling and capability to interface
with OS Amoeba at Centrum Wiskunde and Informatica. It first appeared in 1991.
Python 2.0 was released in the year 2000 and Python 3.0 was released in the year 2008.
The language was named Python after the famous British television comedy show
Monty Python's Flying Circus, which was one of Guido's favourite television
programmes. Here we will see why Python has suddenly influenced our lives and the
various applications that use Python and its implementations.
4.3.1 Why Python?
Now you might be suddenly bogged with the question, why Python? According
to Institute of Electrical and Electronics Engineers (IEEE) 2016 ranking Python ranked
third after C and Java. As per Indeed.com's data of 2016, the Python job market search
ranked fifth. Clearly, all the data points to the ever rising demand in the job market for
Python. It’s a cool language if you want to learn just for fun or if you want to build
your career around Python, you will adore the language. At school level, many schools

28
have started including Python programming for kids. With new technologies taking the
market by surprise Python has been playing a dominant role. Whether it is cloud
platform, mobile app development, Big Data, IoT with Raspberry Pi, or the new Block
chain technology, Python is being seen as a niche language platform to develop and
deliver scalable and robust applications.
Some key features of the language are:
 Python programs can run on any platform, you can carry code created in
Windows machine and run it on Mac or Linux
 Python has inbuilt large library with prebuilt and portable functionality, also
known as the standard library
 Python is an expressive language
 Python is free and open source
 Python code is about one third of the size of equivalent C++ and Java code
 Python can be both dynamically and strongly typed--dynamically typed means it
is a type of variable that is interpreted at runtime, which means, in Python, there
is no need to define the type (int or float) of the variable
4.3.2 Python applications
One of the most famous platforms where Python is extensively used is YouTube. The
other places where you will find Python being extensively used are the special effects
in Hollywood movies, drug evolution and discovery, traffic control systems, ERP
systems, cloud hosting, e-commerce platform, CRM systems, and whatever field you
can think of.
4.3.3 Versions
At the time of writing this book, two main versions of the Python programming
language were available in the market, which are Python 2.x and Python 3.x. The stable
release as of writing the book were Python 2.7.13 and Python 3.6.0.

29
4.3.4 Implementations of Python
Major implementations include CPython, Jpython, Iron Python, Micro Python,
and PyPy.
4.3.5 Installation
Here we will look forward to the installation of Python on three different OS
platforms, namely, Windows, Linux, and Mac OS. Let's begin with the Windows
platform.
4.4 CLASS DIAGRAM

In software engineering, a class diagram in the Unified Modeling Language


(UML) is a type of static structure diagram that describes the structure of a system by
showing the system's classes, their attributes, operations (or methods), and the
relationships among objects.

Fig 4.1 Class diagram

30
CHAPTER 5

RESULTS AND DISCUSSION

Data set has been collected from open source Kaggle website with different
attributes. Below figure 5.1 shows the data set cases.

Fig 5.1: Input Data Formation

The below figure shows training loss for ANN model for the corresponding data
set. The loss function of the model achieved a minimum error value for varying
iterations.

31
Fig 5.2 ANN Training result

Fig 5.3 ANN Model Predicted Result


32
The above figure 5.3 shows the predicted output. For prediction, the individual
processing ANN model adopts only for linear data. This work uses ANN for feature
extraction.

Fig 5.4 ANN Training result

In this figure 5.4 the loss and accuracy can be determined by ANN training result.
The proposed ANN model shows loss values of 0.0348 with the accuracy of 98.35 for
validation data set.

Accuracy is defined as the percentage of correct predictions for the test data. It
can be calculated by dividing the number of correct predictions by the number of total
predictions. From the below figure 5.5 it’s clear that our proposed model has the high
accuracy while comparing other machine learning algorithm.

33
Chart Title
120

100

80

60

40

20

0
F1-Score Accuracy Precision Specificity

RF DT SVM Deep-ANN

Fig 5.5 Performance analysis – Accuracy

Models F1-Score Accuracy Precision Specificity

RF 89.46 84.43 87.76 78.18

DT 92.92 89.76 92.13 85.39

SVM 90.38 86.32 89.06 79.87

Deep-ANN 94.76 94.84 97.61 92.47

Table 5.1 Comparison of Results

The tables 5.1 compare the performance of other machine learning algorithm.
The comparison of result is ANN having high accuracy.
34
CHAPTER 6

CONCLUSION

The application of agriculture networking technology is need of the modern


agricultural development, but also an important symbol of the future level of
agricultural development; it will be the future direction of agricultural development.
After building the agricultural crop recommendation system hardware and analyzing
and researching the network hierarchy features, functionality and the corresponding
software architecture of precision agriculture, actually applying the intelligence to the
highly effective and safe agricultural production has a significant impact on ensuring
the efficient use of resources as well as ensuring the efficiency and stability of the
agricultural production.

35
REFERENCES
[1]. Siuli Roy, Somprakash Bandyopadhyay, “A Test-bed on Real-time Monitoring of
Agricultural Parameters using Wireless Sensor Networks for Precision Agriculture”.

[2]. C. Arun, K. Lakshmi Sudha “Agricultural Management using Wireless Sensor


Networks – A Survey” 2012 2nd International Conference on Environment Science and
Biotechnology IPCBEE vol.48 (2012) © (2012)IACSIT Press, Singapore.

[3]. Anurag D, Siuli Roy and Somprakash Bandyopadhyay, “Agro-Sense: Precision


Agriculture using Sensor-based Wireless Mesh Networks”, ITU-T “Innovation in
NGN”, Kaleidoscope Conference, Geneva 12-13 May 2008.

[4]. Yiming Zhou, Xianglong Yang, Liren Wang, Yibin Ying, A wireless design of low-
cost irrigation system using ZigBee technology, 2009 International Conference on
Networks Security, Wireless Communications and Trusted Computing, 978-0-7695-
3610-1/09 , IEEE.

[5]. Ning Wang, Naiqian Zhang, Maohua Wang, “Wireless sensors in agriculture and
food industry—Recent development and future perspective”, published in Computers
and Electronics in Agriculture 50 (2006) 1–14.

[6]. Izzatdin Abdul Aziz, Mohd Hilmi Hasan, Mohd Jimmy Ismail, MazlinaMehat,
Nazleeni Samiha Haron, “Remote Monitoring in Agricultural Greenhouse Using
Wireless Sensor and Short Message Service (SMS)”, 2008.

[7]. Jeonghwan Hwang, Changsun Shin, and Hyun Yoe “Study on an Agricultural
Environment Monitoring Server System using Wireless Sensor Networks”,2010.

[8] Zhang xihai, Zhang changli Fang junlong. Smart Sensor Nodes for Wireless Soil
Temperature Monitoring Systems in Precision Agriculture 2009. 237-241.

[9] Bogena H R, Huisman J A, OberdÊrster C, et al. Evaluation of a low cost soil water
content sensor for wireless network applications[J].Journal of Hydrology, 2007, 32-42.
36
[10] Weizheng, S., Yachun W., Zhanliang C., and Hongda W.,” Grading Method of
Leaf Spot Disease Based on Image Processing” International Conference on Computer
Science and Software Engineering - Volume 06 ,PP. 491-494,December 2008.

[11] S. S. Sannakki, V. S. Rajpurohit, V. B. Nargund,and P. Kulkarni, “Diagnosis and


Classification of Grape Leaf Diseases using Neural Networks”, IEEE 4th ICCCNT,
2013.

[12] P. Chaudhary, A. K. Chaudhari, Dr. A. N. Cheeran and S.Godara, “Color


Transform Based Approach for Disease Spot” International Journal of Computer
Science and Telecommunications Volume 3, Issue 6, pp.65-70,June 2012

[13] H. Al-Hiary, S. Bani-Ahmad, M. Reyalat, M. Braik and Z. ALRahamneh, “Fast


and Accurate Detection and Classification of Plant Diseases”, IJCA, Vol-17,No.-1,pp.
31-38, March 2011.

[14] P. Babu, M. S. and Srinivasa Rao, “Leaves recognition using backpropagation


neural network - advice for pest and disease control on crops”. Technical report,
Department of Computer Science & Systems Engineering, Andhra University, India,
www.indiakisan.net on May 2010.

[15] Suman T. and Dhruvakumar T., “Classification of paddy leaf diseases using shape
and color features”, IJEEE, Volume 07, Issue 01, PP.239- 250, Jan- June 2015.

37
CODING

import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
import pandas as pd
import pickle
import click
from PIL import Image
from time import sleep
#RSA
# STEP 1: Generate Two Large Prime Numbers (p,q) randomly
from random import randrange, getrandbits
from tkinter import *
from tkinter import ttk
from tkinter import Menu
from tkinter import messagebox as mbox
# import filedialog module
from tkinter import filedialog
flg=0;
import tkinter as tk
model=load_model("train.h5")
# Function for opening the
# file explorer window
def browseFiles():
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a CSV File",
filetypes = (("CSV files",
"*.csv*"),
("all files",
"*.*")))
# Change label contents
label_file_explorer.configure(text="File Opened: "+filename)
global f
f = filename
def start():
print("Process Started")
38
dataset = pd.read_csv(f)
dataset=dataset.dropna(how="any")
print(dataset)
print(dataset.info())
X = dataset.iloc[:,:].values
print(X)
# load the model from disk
ypred = model.predict(X)
ypred = ypred.argmax()
ypred = ypred.round()
print(ypred)
app = tk.Tk()
if(ypred==0):
print("rice")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Rice")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Rice").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==1):
print("maize")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Maize")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Maize").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==2):
print("chickpea")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is chickpea")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
chickpea").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)

39
app.config(menu=menuBar)
elif(ypred==3):
print("kidneybeans")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is kidneybeans")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
kidneybeans").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==4):
print("pigeonpeas")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is pigeonpeas")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
pigeonpeas").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==5):
print("mothbeans")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is mothbeans")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
mothbeans").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==6):
print("mungbean")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is mungbean")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
mungbean").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==7):

40
print("blackgram")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is blackgram")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
blackgram").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==8):
print("lentil")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is lentil")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
lentil").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==9):
print("pomegranate")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is pomegranate")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
pomegranate").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
app.config(menu=menuBar)
elif(ypred==10):
print("banana")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is banana")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
banana").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==11):
print("mango")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is mango")

41
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
mango").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==12):
print("grapes")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Grapes")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Grapes").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==13):
print("watermelon")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is watermelon")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
watermelon").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==14):
print("muskmelon")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is muskmelon")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
muskmelon").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==15):
print("apple")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Apple")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Apple").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==16):
print("orange")

42
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is orange")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
orange").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==17):
print("papaya")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Papaya")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Papaya").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==18):
print("coconut")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Coconut")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Coconut").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==19):
print("cotton")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Cotton")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Cotton").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
elif(ypred==20):
print("jute")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Jute")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Jute").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)

43
elif(ypred==21):
print("Coffee")
label_file_explorer.configure(text="Result for the Data: Predicted crop for cultivation
is Coffee")
app.title("Crop Predicition")
ttk.Label(app, text="Result for the Data: Predicted crop for cultivation is
Coffee").grid(column=0,row=0,padx=20,pady=30)
menuBar = Menu(app)
if __name__ == '__main__':
window = Tk()
# Set window title
window.title('Crop Predicition')
# Set window size
window.geometry("700x400")
#Set window background color
window.config(background = "white")
# Create a File Explorer label
label_file_explorer = Label(window,
text = "Please give Input Data",
width = 100, height = 4,
fg = "blue")
button_explore = Button(window,
text = "Browse Crop prediction data file",
command = browseFiles)
button_exit = Button(window,
text = "exit",
command = exit)
button_start = Button(window,
text = "Start Analyzing Crop prediction data file",
command = start)
# Grid method is chosen for placing
# the widgets at respective positions
# in a table like structure by
# specifying rows and columns
label_file_explorer.grid(column = 1, row = 1, padx=5, pady=5)
button_explore.grid(column = 1, row = 3, padx=5, pady=5)
button_exit.grid(column = 1,row = 9, padx=5, pady=5)
button_start.grid(column = 1,row = 12, padx=5, pady=5)

44
# Let the window wait for any events
window.mainloop()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.keras as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
import seaborn as sns
import sklearn
from sklearn.ensemble import VotingClassifier
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import confusion_matrix, accuracy_score
data = pd.read_csv("Crop_recommendation.csv")
print(data.info())
data=data.dropna(how="any")
print(d ata)
print(data['label'].value_counts())
data['label'] = data['label'].map({"rice":0,"maize":1,"chickpea":2,
"kidneybeans":3,"pigeonpeas":4,"mothbeans":5

,"mungbean":6,"blackgram":7,"lentil":8,"pomegranate":9,"banana":10

,"mango":11,"grapes":12,"watermelon":13,"muskmelon":14,"apple":15
,"orange":16,"papaya":17,"coconut":18,"cotton":19,"jute":20
,"coffee":21})
print(data.info())
X = data.iloc[:,:-1].values
y = data.iloc[:, 7].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30, random_state =
121)#101
print("Xtrain value")
print(X_train)
from tensorflow.keras.utils import to_categorical

45
y_train = to_categorical(y_train)
ytest = to_categorical(y_test)
y_train
print("ytrain value")
print(y_train)
#### Create the model
model = tf.models.Sequential()
### Add the layers
model.add(tf.layers.Dense(64,input_dim=7,activation='relu')) ## input and a hidden
layer
model.add(tf.layers.Dense(128,activation='relu')) ## hidden layer
model.add(tf.layers.Dense(256,activation='relu')) ## hidden layer
model.add(tf.layers.Dense(512,activation='relu')) ## hidden layer
model.add(tf.layers.Dense(22,activation='softmax')) ## output layer

### compile the model


model.compile(loss="categorical_crossentropy",optimizer='adam',metrics=['accuracy'])
model.fit(X_train,y_train,epochs=200)
model.save("train.h5")
ypred=model.predict(X_test)
import numpy as np
y_pred=np.argmax(ypred,axis=1)
print(y_pred)
print(y_test)
dnn = accuracy_score(y_test, y_pred)
print("confussion Matrix ")
#confusion matrix of DNN
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,y_pred)
print(cm)
print("accuracy score of DNN is ")
print(dnn)
print("")

46

You might also like