---
title: "Crop Recommendation based on Weather variables and Fertilizers"
author: "Muhammad Mohsin Raza"
date: '2021-12-31'
slug: crop-recommendation-based-on-weather-fertilizers
field_notes_topic: agriculture
categories: Data Science
tags:
- R
- tidymodels
- machine learning
- random forest
- xgboost
- svm
- ggplot2
subtitle: ''
summary: 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).
lastmod: '2021-12-31T22:59:44+05:00'
featured: no
image:
  caption: ''
  focal_point: Center
  preview_only: true
projects: []
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  warning = FALSE,
  message = FALSE,
  R.options = list,
  dpi = 300
)
```

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](https://www.kaggle.com/atharvaingle/crop-recommendation-dataset) for only the agronomic and commercially grown crops. The data can be downloaded using this [link](https://www.kaggle.com/atharvaingle/crop-recommendation-dataset).

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

```{r message=FALSE, warning=FALSE}
# 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

```{r message=FALSE, warning=FALSE}
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 `skim` package that provides a very handy `skimr` function that can quickly provide an abstract summary of the data.

```{r}
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

```{r}
crop %>% 
  plot_histogram(ggtheme = theme_bw(), geom_histogram_args = list(fill = "steelblue"))
```

## Nominal variables

```{r}
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

```{r}
agro <- crop %>%
  filter(label %in% c("chickpea", "coffee", "cotton", "lentil", "maize", "rice")) %>% 
  mutate(label = factor(label))
```

## Features distribution

```{r}
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

```{r}
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

```{r}
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

```{r}
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.

```{r fig.width=8, message=FALSE}
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.

```{r fig.height=10, fig.width=10, message=FALSE}
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

```{r}
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

```{r}
# create CV object from training data
agro_cv <- vfold_cv(agro_train)
```

## Define the recipe

```{r}
# define the recipe
agro_recipe <- recipe(label ~ ., data = agro) %>%
  step_normalize(all_numeric())
```

## Random Forest

```{r}
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

```{r}
rf_workflow <- workflow() %>%
  add_model(rf_model) %>% 
  add_recipe(agro_recipe)
```

## Model tuning

```{r}
# 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

```{r}
# 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.

```{r}
param_final <- rf_tune_results %>%
  select_best(metric = "accuracy")

param_final
```

#### Final model

```{r}
rf_workflow <- rf_workflow %>%
  finalize_workflow(param_final)
```

### Model testing

```{r}
# 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

```{r}
test_predictions <- rf_fit %>% 
  collect_predictions()

test_predictions
```

#### Confusion matrix

```{r}
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

```{r}
final_model <- fit(rf_workflow, agro)
final_model
```

### Variable importance

```{r}
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

```{r}
## SVM
svm_model <- 
  svm_poly() %>%
  set_engine("kernlab") %>%
  set_mode("classification") 

svm_model

# show what will be tuned
svm_model %>%    
  parameters() 
```

### Workflow

```{r}
svm_workflow <- workflow() %>%
  add_model(svm_model) %>% 
  add_recipe(agro_recipe)
```

### Model testing

```{r}
# fit on the training set and evaluate on test set
svm_fit <- svm_workflow %>%
  last_fit(agro_split)
```

#### Model metrics

```{r}
svm_performance <- svm_fit %>% 
  collect_metrics()

svm_performance
```

-   Model is predicting crops with high accuracy.

#### Generate predictions from the test set

```{r}
test_predictions <- svm_fit %>% 
  collect_predictions()

test_predictions
```

#### Confusion matrix

```{r}
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

```{r}
final_model <- fit(svm_workflow, agro)
final_model
```

## XGBoost

```{r}
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

```{r}
xgb_workflow <- workflow() %>%
  add_formula(label ~ .) %>%
  add_model(xgb_model)

xgb_workflow
```

### Model tuning

```{r}
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

```{r}
# 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

```{r}
param_final <- xgb_tune_results %>%
  select_best(metric = "accuracy")

param_final
```

#### Final model

```{r}
xgb_workflow <- xgb_workflow %>%
  finalize_workflow(param_final)
```

### Model testing

```{r}
# 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

```{r}
test_predictions <- xgb_fit %>% 
  collect_predictions()

test_predictions
```

#### Confusion matrix

```{r}
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

```{r fig.height=5, fig.width=15}
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!!!
