Prasad Chaskar's other Models Reports

Major Concepts

 

Sign-Up/Login to access Several ML Models and also Deploy & Monetize your own ML solutions for free

Models Home » Domain Usecases » Agriculture » Crop Prediction

Crop Prediction

Models Status

Model Overview

Crop Recommendation:


Based on predicted rainfall, soil contents and weather parameters the system will recommend the most suitable crop for cultivation. This system also provides details about required fertilizers like Nitrogen(N), Phosphorus (P) and potassium(K) in Kg per hectare and display the required seed for a cultivation in Kg per acre for recommended crop.This system as contain some other feature such as display thecurrent market price and approximated yield in quintal per acre for recommended crop. Those all details will helps to farmers for choosing the most profitable crop.
Crop prediction process being with the load external crop diabetes. Once the dataset read then pre-processing will be done. After the pre-processing train the model using various models like logistic regression, support vector machine, random forest and check how each model will perform for unseen data and choose model which give high accuracy or perform well.


About Dataset :

This dataset was build by augmenting datasets of rainfall, climate and fertilizer data available for India.

Data field

N - ratio of Nitrogen content in soil
P - ratio of Phosphorous content in soil
K - ratio of Potassium content in soil
temperature - temperature in degree Celsius
humidity - relative humidity in %
ph - ph value of the soil
rainfall - rainfall in mm


Dataset Link : https://www.kaggle.com/atharvaingle/crop-recommendation-dataset

Coding Part :
Import Libraries :


import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split​

Read Dataset :

crop_df = pd.read_csv('Crop_recommendation.csv')
crop_df.head()​


Dataset contains 2200 records and 8 columns.



Check whether Dataset contains NULL values or not :

crop_df.isnull().sum()





There are no null values present in our dataset.
Create new column to assign number to each crop :

crop_df['no_label'] = pd.Categorical(crop_df.label).codes

Exploratory Data Analysis :
1]Nitrogen :


plt.figure(figsize=(8,7))
sns.histplot(x='N',data=crop_df,color='b');
plt.title("Nitrogen for crops",{'fontsize':20});


Importance of Nitrogen :

Nitrogen is an essential nutrient for plant growth, development and reproduction.Soil nitrogen exists in three general forms: organic nitrogen compounds, ammonium (NH₄⁺) ions and nitrate (NO₃⁻) ions.

2] Potassium


plt.figure(figsize=(8,7))
sns.histplot(x='K',data=crop_df,color='b');
plt.title("Potassium for crops",{'fontsize':20});





Importance of Potassium in Plants:

The rate of respiration by plants is largely the determining factor for proper uptake and transport of potassium by plants.

Potassium also facilitates protein and starch synthesis in plants.

It activates enzymes responsible for specific functions.
3] Phosphorus
plt.figure(figsize=(8,7))
sns.histplot(x='P',data=crop_df,color='b');
plt.title("Phosphorus for crops",{'fontsize':20});


Importance of Phosphorus to Plants :




Phosphorus is important for cell division and development of new tissues.

Adding phosphorus to plats helps for root growth.

It also recommend for early growth of plants.
4]Temperature

plt.figure(figsize=(10,6))
sns.boxplot(x=crop_df.temperature);



5]Humidity


plt.figure(figsize=(10,6))
sns.boxplot(x=crop_df.humidity);


6]PH


plt.figure(figsize=(8,7))
sns.histplot(x='ph',data=crop_df,color='b');
plt.title("PH for crops",{'fontsize':20});


pH stands for ‘potential of hydrogen’ and refers to the amount of hydrogen found in the soil.

Importance of PH to plants :

pH can affect a plant’s ability to absorb vital nutrients from the soil. If pH is too acidic or alkaline, this can stunt or retard root growth and consequently, restrict water and nutrient uptake.


7]Rainfall

plt.figure(figsize=(8,7))
sns.histplot(x='rainfall',data=crop_df,color='b');
plt.title("Rainfall feature",{'fontsize':20});


Split data


X = crop_df.drop(['label','no_label'],axis=1)
y = crop_df.no_label

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)


Feature Scaling

scalar = StandardScaler()
X_train = scalar.fit_transform(X_train)
X_test = scalar.transform(X_test)




Build Model


models = {
LogisticRegression(max_iter=500):'Logistic Regression',
RandomForestClassifier():'Random Forest',
SVC():'Support Vector Machine'
}
for m in models.keys():
m.fit(X_train,y_train)
for model,name in models.items():
print(f"Accuracy Score for {name} is : ",model.score(X_test,y_test)*100,"%")​




rf = RandomForestClassifier()
rf.fit(X_train,y_train)

y_pred = rf.predict(X_test)

Classification Report :



crop_labels = {0:'apple',1:'banana',2:'blackgram',3:'chickpea',4:'coconut',5:'coffee',6:'cotton',7:'grapes',8:'jute',9:'kidneybeans',

9:'lentil',10:'maize',12:'mango',13:'mothbeans',14:'mungbean',15:'muskmelon',16:'orange',17:'papaya',18:'pigeonpeas',19:'pomegranate',20:'rice',21:'watermelon'}




print(classification_report(y_test,y_pred))




Confusion Matrix :

class_names = np.arange(0,21)
fig,ax = plt.subplots()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks,class_names)
plt.yticks(tick_marks,class_names)
cnf_matrix = confusion_matrix(y_test,y_pred)
sns.heatmap(pd.DataFrame(cnf_matrix), annot = True,fmt = 'd')
ax.xaxis.set_label_position('top')
plt.tight_layout()
plt.title(f'Confusion Matrix for Random Forest', {'fontsize':20})
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
plt.show()


Thank You ):


































0 comments