CONTENT 1
CONTENT 1
INTRODUCTION
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
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.
Crop science: by matching farming practices more closely to crop needs (e.g. fertilizer
inputs);
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
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
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.
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.
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.
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
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.
8
1.4.2 MACHINE LEARNING
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.
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.
14
CHAPTER 3
METHODOLOGY
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
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
Modules
• Data Preparation
• Feature extraction
• Deep Dense ANN model building
• Performance analysis
19
3.2.1 DEEP DENSE ARTIFICIAL NEURAL NETWORK
What is ANN?
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.
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.
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
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.
3.2.5.1 ARCHITECTURE
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.
Outputs
Activation function
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
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
30
CHAPTER 5
Data set has been collected from open source Kaggle website with different
attributes. Below figure 5.1 shows the data set cases.
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
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
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
35
REFERENCES
[1]. Siuli Roy, Somprakash Bandyopadhyay, “A Test-bed on Real-time Monitoring of
Agricultural Parameters using Wireless Sensor Networks for Precision Agriculture”.
[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.
[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
46