|
| 1 | +# Crop-Recommendation-Model |
| 2 | + |
| 3 | +<div align='center'> |
| 4 | + <img src='https://images.app.goo.gl/DR673P8iCBwThkgk9' alt='' /> |
| 5 | +</div> |
| 6 | + |
| 7 | +## 🎯 AIM |
| 8 | + |
| 9 | +It is an AI-powered Crop Recommendation System that helps farmers and agricultural stakeholders determine the most suitable crops for cultivation based on environmental conditions. The system uses machine learning models integrated with Flask to analyze key parameters and suggest the best crop to grow in a given region. |
| 10 | + |
| 11 | +## 📊 DATASET LINK |
| 12 | + |
| 13 | +[https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset/data](https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset/data) |
| 14 | + |
| 15 | +## 📓 NOTEBOOK |
| 16 | + |
| 17 | +[https://www.kaggle.com/code/kashishkhurana1204/crop-recommendation-system](https://www.kaggle.com/code/kashishkhurana1204/crop-recommendation-system) |
| 18 | + |
| 19 | +??? Abstract "Kaggle Notebook" |
| 20 | + |
| 21 | + <iframe |
| 22 | + src="https://www.kaggle.com/code/kashishkhurana1204/recommendation-system" |
| 23 | + height="600" |
| 24 | + style="margin: 0 auto; width: 100%; max-width: 950px;" |
| 25 | + frameborder="0" |
| 26 | + scrolling="auto" |
| 27 | + title="Crop Recommendation System"> |
| 28 | + </iframe> |
| 29 | + |
| 30 | +## ⚙️ TECH STACK |
| 31 | + |
| 32 | +| **Category** | **Technologies** | |
| 33 | +|--------------------------|-----------------------------------------| |
| 34 | +| **Languages** | Python | |
| 35 | +| **Libraries/Frameworks** | Pandas, Numpy, Matplotlib, Scikit-learn | |
| 36 | +| **Tools** | Github, Jupyter, VS Code | |
| 37 | + |
| 38 | +--- |
| 39 | + |
| 40 | +## 📝 DESCRIPTION |
| 41 | + |
| 42 | + |
| 43 | +!!! info "What is the requirement of the project?" |
| 44 | + - To provide accurate crop recommendations based on environmental conditions. |
| 45 | + - To assist farmers in maximizing yield and efficiency. |
| 46 | + |
| 47 | +??? info "How is it beneficial and used?" |
| 48 | + - Helps in optimizing agricultural planning. |
| 49 | + - Reduces trial-and-error farming practices. |
| 50 | + |
| 51 | + |
| 52 | +??? info "How did you start approaching this project? (Initial thoughts and planning)" |
| 53 | + - Initial thoughts : The goal is to help farmers determine the most suitable crops based on their field’s environmental conditions. |
| 54 | + |
| 55 | + - Dataset Selection : I searched for relevant datasets on Kaggle that include soil properties, weather conditions, and nutrient levels such as nitrogen (N), phosphorus (P), and potassium (K). |
| 56 | + |
| 57 | + - Initial Data Exploration : I analyzed the dataset structure to understand key attributes like soil pH, humidity, rainfall, and nutrient values, which directly impact crop suitability. |
| 58 | + |
| 59 | + - Feature Analysis : Studied how different environmental factors influence crop growth and identified the most significant parameters for prediction. |
| 60 | + |
| 61 | + - Model Selection & Implementation : Researched various ML models and implemented algorithms like Naïve Bayes, Decision Trees, and Random Forest to predict the best-suited crops. |
| 62 | + |
| 63 | +??? info "Mention any additional resources used (blogs, books, chapters, articles, research papers, etc.)." |
| 64 | + - [https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset/data](https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset/data) |
| 65 | + |
| 66 | + |
| 67 | +--- |
| 68 | + |
| 69 | +## 🔍 EXPLANATION |
| 70 | + |
| 71 | +### DATASET OVERVIEW & FEATURE DETAILS |
| 72 | + |
| 73 | +📂 dataset.csv |
| 74 | +| **Feature**| **Description** | **Data Type** | |
| 75 | +|------------|-----------------|----------------| |
| 76 | +| Soil_pH | Soil pH level | float | |
| 77 | +| Humidity | Humidity level | float | |
| 78 | +| Rainfall | Rainfall amount | float | |
| 79 | +| N | Nitrogen level | int64 | |
| 80 | +| P | Phosphorus level| int64 | |
| 81 | +| K | Potassium level | int64 | |
| 82 | +|Temperature | Temperature | float | |
| 83 | +| crop | Recommended crop| categorical | |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | +### 🛤 PROJECT WORKFLOW |
| 88 | + |
| 89 | +```mermaid |
| 90 | + graph |
| 91 | + Start -->|No| End; |
| 92 | + Start -->|Yes| Import_Libraries --> Load_Dataset --> Data_Cleaning --> Feature_Selection --> Train_Test_Split --> Define_Models; |
| 93 | + Define_Models --> Train_Models --> Evaluate_Models --> Save_Best_Model --> Develop_Flask_API --> Deploy_Application --> Conclusion; |
| 94 | + Deploy_Application -->|Error?| Debug --> Yay!; |
| 95 | +
|
| 96 | +``` |
| 97 | + |
| 98 | + |
| 99 | +=== "Import Necessary Libraries" |
| 100 | + - First, we import all the essential libraries needed for handling, analyzing, and modeling the dataset. |
| 101 | + - This includes libraries like Pandas for data manipulation, Numpy for numerical computations, Matplotlib and Seaborn for data visualization, and Scikit-learn for machine learning models, evaluation, and data preprocessing. |
| 102 | + - These libraries will enable us to perform all required tasks efficiently. |
| 103 | + |
| 104 | +=== "Load Dataset" |
| 105 | + - We load the dataset using Pandas `read_csv()` function. The dataset contains crop data, which is loaded with a semicolon delimiter. |
| 106 | + - After loading, we inspect the first few rows to understand the structure of the data and ensure that the dataset is correctly loaded. |
| 107 | + |
| 108 | +=== "Data Cleaning Process" |
| 109 | + Data cleaning is a crucial step in any project. In this step: |
| 110 | + |
| 111 | + - Handle missing values, remove duplicates, and ensure data consistency. |
| 112 | + - Convert categorical variables if necessary and normalize numerical values. |
| 113 | + |
| 114 | +=== "Visualizing Correlations Between Features" |
| 115 | + |
| 116 | + - Use heatmaps and scatter plots to understand relationships between features and how they impact crop recommendations. |
| 117 | + |
| 118 | +=== "Data Preparation - Features (X) and Target (y)" |
| 119 | + |
| 120 | + - Separate independent variables (environmental parameters) and the target variable (recommended crop). |
| 121 | + |
| 122 | +=== "Split the Data into Training and Test Sets" |
| 123 | + |
| 124 | + - Use train_test_split() from Scikit-learn to divide data into training and testing sets, ensuring model generalization. |
| 125 | + |
| 126 | +=== "Define Models" |
| 127 | + We define multiple regression models to train and evaluate on the dataset: |
| 128 | + |
| 129 | + - **RandomForestRegressor**: A robust ensemble method that performs well on non-linear datasets. |
| 130 | + - **Naive Bayes**: A probabilistic classifier based on Bayes' theorem, which assumes independence between features and is effective for classification tasks. |
| 131 | + - **DecisionTreeRegressor**: A decision tree-based model, capturing non-linear patterns and interactions. |
| 132 | + |
| 133 | +=== "Train and Evaluate Each Model" |
| 134 | + |
| 135 | + - Fit models using training data and evaluate performance using accuracy, precision, recall, and F1-score metrics. |
| 136 | + |
| 137 | +=== "Visualizing Model Evaluation Metrics" |
| 138 | + |
| 139 | + - Use confusion matrices, precision-recall curves, and ROC curves to assess model performance. |
| 140 | + |
| 141 | +== "Conclusion and Observations" |
| 142 | + |
| 143 | + **Best-Performing Models and Insights Gained:** |
| 144 | + |
| 145 | + - The Random Forest model provided the highest accuracy and robustness in predictions. |
| 146 | + |
| 147 | + - Decision Tree performed well but was prone to overfitting on training data. |
| 148 | + |
| 149 | + - Naïve Bayes, though simple, showed competitive performance for certain crop categories. |
| 150 | + |
| 151 | + - Feature importance analysis revealed that soil pH and nitrogen levels had the most significant impact on crop recommendation. |
| 152 | + |
| 153 | + **Potential Improvements and Future Enhancements:** |
| 154 | + |
| 155 | + - Implement deep learning models for better feature extraction and prediction accuracy. |
| 156 | + |
| 157 | + - Expand the dataset by incorporating satellite and real-time sensor data. |
| 158 | + |
| 159 | + - Integrate weather forecasting models to enhance crop suitability predictions. |
| 160 | + |
| 161 | + - Develop a mobile-friendly UI for better accessibility to farmers. |
| 162 | + |
| 163 | +--- |
| 164 | + |
| 165 | +### 🖥 CODE EXPLANATION |
| 166 | + |
| 167 | +=== "Code to compute F1-score, Precision, and Recall" |
| 168 | + |
| 169 | + ```py |
| 170 | + from sklearn.metrics import precision_score, recall_score, f1_score, classification_report |
| 171 | + |
| 172 | + # Initialize a dictionary to store model scores |
| 173 | + model_scores = {} |
| 174 | + |
| 175 | + # Iterate through each model and compute evaluation metrics |
| 176 | + for name, model in models.items(): |
| 177 | + print(f"Evaluating {name}...") |
| 178 | + |
| 179 | + # Train the model |
| 180 | + model.fit(x_train, y_train) |
| 181 | + |
| 182 | + # Predict on the test set |
| 183 | + y_pred = model.predict(x_test) |
| 184 | + |
| 185 | + # Compute metrics |
| 186 | + precision = precision_score(y_test, y_pred, average='weighted') |
| 187 | + recall = recall_score(y_test, y_pred, average='weighted') |
| 188 | + f1 = f1_score(y_test, y_pred, average='weighted') |
| 189 | + |
| 190 | + # Store results |
| 191 | + model_scores[name] = { |
| 192 | + 'Precision': precision, |
| 193 | + 'Recall': recall, |
| 194 | + 'F1 Score': f1 |
| 195 | + } |
| 196 | + |
| 197 | + # Print results for each model |
| 198 | + print(f"Precision: {precision:.4f}") |
| 199 | + print(f"Recall: {recall:.4f}") |
| 200 | + print(f"F1 Score: {f1:.4f}") |
| 201 | + print("\nClassification Report:\n") |
| 202 | + print(classification_report(y_test, y_pred)) |
| 203 | + print("-" * 50) |
| 204 | + |
| 205 | + # Print a summary of all model scores |
| 206 | + print("\nSummary of Model Performance:\n") |
| 207 | + for name, scores in model_scores.items(): |
| 208 | + print(f"{name}: Precision={scores['Precision']:.4f}, Recall={scores['Recall']:.4f}, F1 Score={scores['F1 Score']:.4f}") |
| 209 | + |
| 210 | + ``` |
| 211 | + |
| 212 | + - This code evaluates multiple machine learning models and displays performance metrics such as Precision, Recall, F1 Score, and a Classification Report for each model. |
| 213 | + |
| 214 | +--- |
| 215 | + |
| 216 | +### ⚖️ PROJECT TRADE-OFFS AND SOLUTIONS |
| 217 | + |
| 218 | +=== "Trade Off 1" |
| 219 | + - **Trade-off**: Accuracy vs. Computational Efficiency |
| 220 | + - **Solution**: Optimized hyperparameters and used efficient algorithms. |
| 221 | + |
| 222 | +=== "Trade Off 2" |
| 223 | + - **Trade-off**: Model interpretability vs complexity. |
| 224 | + - **Solution**: Selected models balancing accuracy and interpretability. |
| 225 | + |
| 226 | +--- |
| 227 | + |
| 228 | +## 🖼 SCREENSHOTS |
| 229 | + |
| 230 | +!!! tip "Visualizations of different features" |
| 231 | + |
| 232 | + === "HeatMap" |
| 233 | +  |
| 234 | + |
| 235 | + === "Model Comparison" |
| 236 | +  |
| 237 | + |
| 238 | + |
| 239 | +--- |
| 240 | + |
| 241 | +## 📉 MODELS USED AND THEIR EVALUATION METRICS |
| 242 | + |
| 243 | +| Model | Accuracy | Precision | Recall |F1-score| |
| 244 | +|---------------------------|----------|-----------|--------|--------| |
| 245 | +| Naive Bayes | 99.54% | 99.58% | 99.55% | 99.54% | |
| 246 | +| Random Forest Regressor | 99.31% | 99.37% | 99.32% | 99.32% | |
| 247 | +| Decision Tree Regressor | 98.63% | 98.68% | 98.64% | 98.63% | |
| 248 | + |
| 249 | +--- |
| 250 | + |
| 251 | +## ✅ CONCLUSION |
| 252 | + |
| 253 | +### 🔑 KEY LEARNINGS |
| 254 | + |
| 255 | +!!! tip "Insights gained from the data" |
| 256 | + - Soil conditions play a crucial role in crop recommendation. |
| 257 | + - Environmental factors significantly impact crop yield. |
| 258 | + |
| 259 | +??? tip "Improvements in understanding machine learning concepts" |
| 260 | + - Feature engineering and hyperparameter tuning. |
| 261 | + - Deployment of ML models in real-world applications. |
| 262 | + |
| 263 | +--- |
| 264 | + |
| 265 | +### 🌍 USE CASES |
| 266 | + |
| 267 | +=== "Application 1" |
| 268 | + **Application of FarmSmart in precision farming.** |
| 269 | + |
| 270 | + - FarmSmart helps optimize resource allocation, enabling farmers to make data-driven decisions for sustainable and profitable crop production. |
| 271 | + [https://github.com/Kashishkh/FarmSmart](https://github.com/Kashishkh/FarmSmart) |
| 272 | + |
| 273 | +=== "Application 2" |
| 274 | + **Use in government agricultural advisory services.** |
| 275 | + |
| 276 | + - Government agencies can use FarmSmart to provide region-specific crop recommendations, improving food security and agricultural productivity through AI-driven insights. |
| 277 | + |
| 278 | + |
| 279 | + |
0 commit comments