Crop Recommendation based on Weather variables and Fertilizers
Download the tutorial CSV · Download the R Markdown source
In this blog post, I’ll show that how we can use different classification algorithms to perform crop recommendation based on weather variables such as Temperature, Humidity and Rainfall, and fertilizers (Nitrogen, Phosphorus and Potassium). For the classification purpose, I will use crop data for only the agronomic and commercially grown crops. The data can be downloaded using this link.
At first, I’ll run some exploratory data analysis (EDA) to understand patterns and trends in the data set and then will move towards data analysis. In this post, I’ll use random forest, support vector machine and Xgboost models in the tidymodels framework to recommend crops based on weather variables and fertilizers.
Load libraries
# Data science
library(tidyverse)
library(janitor)
library(DataExplorer)
library(skimr)
# Modeling
library(tidymodels)
# Visualization
library(ggrepel)
library(GGally)
library(vip)
library(patchwork)
# Tables
library(gt)
Upload data
crop <- read_csv("Crop_recommendation.csv")
Exploratory data analysis
Exploratory data analysis (EDA) is vital in swiftly understanding the data structure and patterns in it. I’ll demonstrate different steps in EDA.
Data structure
- In this step of understanding data structure, I’ll use the
skimpackage that provides a very handyskimrfunction that can quickly provide an abstract summary of the data.
skim(crop)
- The data contain information of 7 unique features for 22 unique crops.
- Now, I’ll explore these features in general and by each crop.
Numeric variables
crop %>%
plot_histogram(ggtheme = theme_bw(), geom_histogram_args = list(fill = "steelblue"))
Nominal variables
crop %>%
plot_bar(ggtheme = theme_bw())
- Each crop has around 100 observations.
Agronomic crops
Now, I’ll filter the data for the agronomic crops or commercially grown crops only. These crops include:
1. Chickpea
2. Coffee
3. Cotton
4. Lentil
5. Maize
6. Rice
agro <- crop %>%
filter(label %in% c("chickpea", "coffee", "cotton", "lentil", "maize", "rice")) %>%
mutate(label = factor(label))
Features distribution
agro %>%
pivot_longer(N:rainfall, names_to = "Feature", values_to = "value") %>%
ggplot(aes(x = value)) +
geom_histogram(fill = "steelblue") +
labs(x = "Value", y = "Count", fill = NULL) +
theme_bw() +
facet_wrap(~Feature, scales = "free")
By Crop
agro %>%
pivot_longer(N:rainfall, names_to = "Feature", values_to = "value") %>%
ggplot(aes(x = value, fill = label)) +
geom_histogram(alpha = 0.65) +
labs(x = "Value", y = "Count", fill = NULL) +
theme_test() +
facet_wrap(~Feature, scales = "free")
- Histograms clearly reveals that distributions of weather and fertilizer variables are quite different for each crop.
Density charts
agro %>%
pivot_longer(N:rainfall, names_to = "Feature", values_to = "value") %>%
ggplot(aes(x = value, fill = label)) +
geom_density(alpha = 0.5) +
labs(fill = NULL) +
theme_test() +
facet_wrap(~Feature, scales = "free")
Box plots
agro %>%
pivot_longer(N:rainfall, names_to = "Feature", values_to = "value") %>%
ggplot(aes(x = label, y = value)) +
geom_boxplot() +
labs(x = "Population", y = "Count", fill = NULL) +
theme_bw() +
coord_flip() +
facet_wrap(~Feature, scales = "free_x", ncol = 4) +
theme(legend.position = "top")
Correlation between features
Pooled data
- The features are significantly correlated in the pooled data.
agro %>%
ggpairs(columns = 1:7)
By crop
- When the features were grouped by crop type, the significance of the relationship between features has been diminished.
agro %>%
ggpairs(columns = 1:7, ggplot2::aes(colour=label))

- Clusters of features are clearly visible which means that there is highly likely that the majority of crops will be accurately classified.
Data Analysis
Data splitting and Resampling
set.seed(12345)
# split the data into trainng (75%) and testing (25%)
agro_split <- initial_split(agro, prop = 3/4)
agro_split
# extract training and testing sets
agro_train <- training(agro_split)
agro_test <- testing(agro_split)
Splitting data for Cross Validation
# create CV object from training data
agro_cv <- vfold_cv(agro_train)
Define the recipe
# define the recipe
agro_recipe <- recipe(label ~ ., data = agro) %>%
step_normalize(all_numeric())
Random Forest
rf_model <-
rand_forest() %>%
set_args(mtry = tune()) %>%
set_engine("ranger", importance = "permutation") %>%
set_mode("classification")
rf_model
# show what will be tuned
rf_model %>%
parameters()
Workflow
rf_workflow <- workflow() %>%
add_model(rf_model) %>%
add_recipe(agro_recipe)
Model tuning
# specify which values want to try
rf_grid <- expand.grid(mtry = c(2, 3, 4, 5, 6))
# extract results
rf_tune_results <- rf_workflow %>%
tune_grid(resamples = agro_cv, #CV object
grid = rf_grid, # grid of values to try
metrics = metric_set(accuracy, precision, recall) # metrics we care about
)
Model metrics
# print results
rf_tune_results %>%
collect_metrics()
# Accuracy
rf_tune_results %>%
show_best(metric = "accuracy")
# Plotting metrics
autoplot(rf_tune_results)

Finalize the workflow
Select the best model
- I chose the best model based on accuracy.
param_final <- rf_tune_results %>%
select_best(metric = "accuracy")
param_final
Final model
rf_workflow <- rf_workflow %>%
finalize_workflow(param_final)
Model testing
# fit on the training set and evaluate on test set
rf_fit <- rf_workflow %>%
last_fit(agro_split)
# Metrics
test_performance <- rf_fit %>%
collect_metrics()
test_performance
- Model is predicting crops with high accuracy.
Generate predictions from the test set
test_predictions <- rf_fit %>%
collect_predictions()
test_predictions
Confusion matrix
cm_rf <- test_predictions %>%
conf_mat(truth = label, estimate = .pred_class)
# Plot the confusion matrix
p1 <- autoplot(cm_rf, type = "heatmap") +
scale_fill_gradient(low="#D6EAF8",high = "#2E86C1") +
labs(title = "Random Forest") +
theme(plot.title = element_text(hjust = 0.5))
p1

Fitting and using final model
final_model <- fit(rf_workflow, agro)
final_model
Variable importance
rf_fit %>%
pluck(".workflow", 1) %>%
extract_fit_parsnip() %>%
vip(aesthetics = list(fill = "steelblue")) +
theme_minimal()

- Both humidity and rainfall are highly important when classifying agronomic crops.
Support Vector Machine
## SVM
svm_model <-
svm_poly() %>%
set_engine("kernlab") %>%
set_mode("classification")
svm_model
# show what will be tuned
svm_model %>%
parameters()
Workflow
svm_workflow <- workflow() %>%
add_model(svm_model) %>%
add_recipe(agro_recipe)
Model testing
# fit on the training set and evaluate on test set
svm_fit <- svm_workflow %>%
last_fit(agro_split)
Model metrics
svm_performance <- svm_fit %>%
collect_metrics()
svm_performance
- Model is predicting crops with high accuracy.
Generate predictions from the test set
test_predictions <- svm_fit %>%
collect_predictions()
test_predictions
Confusion matrix
cm_svm <- test_predictions %>%
conf_mat(truth = label, estimate = .pred_class)
# Plot the confusion matrix
p2 <- autoplot(cm_svm, type = "heatmap") +
scale_fill_gradient(low="#D6EAF8",high = "#2E86C1") +
labs(title = "Support Vector Machine") +
theme(plot.title = element_text(hjust = 0.5))
p2

Fitting and using final model
final_model <- fit(svm_workflow, agro)
final_model
XGBoost
xgb_model <- boost_tree() %>%
set_args(mtry = tune()) %>%
set_engine("xgboost") %>%
set_mode("classification")
xgb_model
# show what will be tuned
xgb_model %>%
parameters()
Workflow
xgb_workflow <- workflow() %>%
add_formula(label ~ .) %>%
add_model(xgb_model)
xgb_workflow
Model tuning
xgb_grid <- grid_latin_hypercube(
finalize(mtry(), agro_train),
size = 30
)
xgb_tune_results <- tune_grid(
xgb_workflow,
resamples = agro_cv,
grid = xgb_grid,
metrics = metric_set(accuracy, precision, recall) # metrics we care about
)
Model metrics
# print results
xgb_tune_results %>%
collect_metrics()
# Accuracy
xgb_tune_results %>%
show_best(metric = "accuracy")
# Plotting metrics
autoplot(xgb_tune_results)

Finalize the workflow
Select the best model
param_final <- xgb_tune_results %>%
select_best(metric = "accuracy")
param_final
Final model
xgb_workflow <- xgb_workflow %>%
finalize_workflow(param_final)
Model testing
# fit on the training set and evaluate on test set
xgb_fit <- xgb_workflow %>%
last_fit(agro_split)
# Metrics
test_performance <- xgb_fit %>%
collect_metrics()
test_performance
- Model is predicting crops with high accuracy.
Generate predictions from the test set
test_predictions <- xgb_fit %>%
collect_predictions()
test_predictions
Confusion matrix
cm_xgb <- test_predictions %>%
conf_mat(truth = label, estimate = .pred_class)
# Plot the confusion matrix
p3 <- autoplot(cm_xgb, type = "heatmap") +
scale_fill_gradient(low="#D6EAF8",high = "#2E86C1") +
labs(title = "XGBoost") +
theme(plot.title = element_text(hjust = 0.5))
p3

All Models
p1 + p2 + p3

Conclusion
- All of the tested models accurately classified agronomic crops.
- I anticipated the same when plotted the distributions of the explanatory variables.
- Both weather and fertilizer variables had distinct distributions in each crop.
- And these models might have optimally learned this information, thus, classifying the crops with excellent accuracy.
- I will use these models in my upcoming notebooks to evaluate their performance in predicting diseased and healthy plots in crop fields.
- Stay Tuned!!!