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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pickle
|
| 4 |
+
from sklearn.pipeline import Pipeline
|
| 5 |
+
from sklearn.preprocessing import StandardScaler, OneHotEncoder
|
| 6 |
+
from sklearn.compose import ColumnTransformer
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Set page config first
|
| 10 |
+
st.set_page_config(
|
| 11 |
+
page_title="Crop Prediction App",
|
| 12 |
+
page_icon="πΎ",
|
| 13 |
+
layout="centered",
|
| 14 |
+
initial_sidebar_state="expanded"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Custom CSS
|
| 18 |
+
st.markdown("""
|
| 19 |
+
<style>
|
| 20 |
+
.title {
|
| 21 |
+
color: #2c3e50;
|
| 22 |
+
text-align: center;
|
| 23 |
+
margin-bottom: 30px;
|
| 24 |
+
}
|
| 25 |
+
.stButton>button {
|
| 26 |
+
background-color: #27ae60;
|
| 27 |
+
color: white;
|
| 28 |
+
border-radius: 8px;
|
| 29 |
+
padding: 10px 20px;
|
| 30 |
+
width: 100%;
|
| 31 |
+
transition: all 0.3s;
|
| 32 |
+
}
|
| 33 |
+
.stButton>button:hover {
|
| 34 |
+
background-color: #2ecc71;
|
| 35 |
+
transform: scale(1.02);
|
| 36 |
+
}
|
| 37 |
+
.input-section {
|
| 38 |
+
background-color: #f8f9fa;
|
| 39 |
+
padding: 20px;
|
| 40 |
+
border-radius: 10px;
|
| 41 |
+
margin-bottom: 20px;
|
| 42 |
+
}
|
| 43 |
+
.prediction-section {
|
| 44 |
+
background-color: #e8f5e9;
|
| 45 |
+
padding: 20px;
|
| 46 |
+
border-radius: 10px;
|
| 47 |
+
margin-top: 20px;
|
| 48 |
+
}
|
| 49 |
+
.step-card {
|
| 50 |
+
background-color: #ffffff;
|
| 51 |
+
border-radius: 10px;
|
| 52 |
+
padding: 15px;
|
| 53 |
+
margin-bottom: 10px;
|
| 54 |
+
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 55 |
+
}
|
| 56 |
+
</style>
|
| 57 |
+
""", unsafe_allow_html=True)
|
| 58 |
+
|
| 59 |
+
# Load model (with error handling)
|
| 60 |
+
@st.cache_resource
|
| 61 |
+
def load_model():
|
| 62 |
+
try:
|
| 63 |
+
with open("lor_f.pkl", "rb") as f:
|
| 64 |
+
model = pickle.load(f)
|
| 65 |
+
return model
|
| 66 |
+
except FileNotFoundError:
|
| 67 |
+
st.error("Model file not found. Please ensure 'lor_f.pkl' exists.")
|
| 68 |
+
return None
|
| 69 |
+
except Exception as e:
|
| 70 |
+
st.error(f"Error loading model: {str(e)}")
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
model = load_model()
|
| 74 |
+
|
| 75 |
+
# App title
|
| 76 |
+
st.markdown("<h1 class='title'>πΎ Smart Crop Prediction</h1>", unsafe_allow_html=True)
|
| 77 |
+
|
| 78 |
+
# Main app sections
|
| 79 |
+
tab1, tab2 = st.tabs(["Prediction", "Project Overview"])
|
| 80 |
+
|
| 81 |
+
with tab1:
|
| 82 |
+
st.subheader("Enter Soil and Weather Conditions")
|
| 83 |
+
|
| 84 |
+
with st.container():
|
| 85 |
+
st.markdown("<div class='input-section'>", unsafe_allow_html=True)
|
| 86 |
+
|
| 87 |
+
col1, col2 = st.columns(2)
|
| 88 |
+
with col1:
|
| 89 |
+
nitrogen = st.slider("Nitrogen (N) level", 1, 140, 50,
|
| 90 |
+
help="Nitrogen content in soil (1-140 kg/ha)")
|
| 91 |
+
phosphorus = st.slider("Phosphorus (P) level", 5, 145, 50,
|
| 92 |
+
help="Phosphorus content in soil (5-145 kg/ha)")
|
| 93 |
+
potassium = st.slider("Potassium (K) level", 5, 205, 50,
|
| 94 |
+
help="Potassium content in soil (5-205 kg/ha)")
|
| 95 |
+
ph_value = st.slider("Soil pH Value", 3.0, 9.9, 6.5, 0.1,
|
| 96 |
+
help="Soil acidity/alkalinity (3.0-9.9 pH)")
|
| 97 |
+
|
| 98 |
+
with col2:
|
| 99 |
+
temperature = st.slider("Temperature (Β°C)", 8.0, 43.0, 25.0, 0.1,
|
| 100 |
+
help="Average temperature (8-43Β°C)")
|
| 101 |
+
humidity = st.slider("Humidity (%)", 14, 99, 60,
|
| 102 |
+
help="Relative humidity (14-99%)")
|
| 103 |
+
rainfall = st.slider("Rainfall (mm)", 20, 298, 100,
|
| 104 |
+
help="Annual rainfall (20-298 mm)")
|
| 105 |
+
|
| 106 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 107 |
+
|
| 108 |
+
if st.button("Predict Optimal Crop", key="predict_btn"):
|
| 109 |
+
if model is None:
|
| 110 |
+
st.error("Model not available. Please check the model file.")
|
| 111 |
+
else:
|
| 112 |
+
try:
|
| 113 |
+
user_data = np.array([[nitrogen, phosphorus, potassium, temperature,
|
| 114 |
+
humidity, ph_value, rainfall]])
|
| 115 |
+
prediction = model.predict(user_data)
|
| 116 |
+
|
| 117 |
+
with st.container():
|
| 118 |
+
st.markdown("<div class='prediction-section'>", unsafe_allow_html=True)
|
| 119 |
+
st.success(f"### Recommended Crop: **{prediction[0]}**")
|
| 120 |
+
|
| 121 |
+
# Add some visual feedback
|
| 122 |
+
st.write("Based on your inputs, the optimal crop for these conditions is:")
|
| 123 |
+
st.markdown(f"<h3 style='text-align: center; color: #27ae60;'>{prediction[0]}</h3>",
|
| 124 |
+
unsafe_allow_html=True)
|
| 125 |
+
|
| 126 |
+
# Add some additional information
|
| 127 |
+
st.markdown("""
|
| 128 |
+
**Tips for better yield:**
|
| 129 |
+
- Maintain proper irrigation
|
| 130 |
+
- Monitor soil nutrients regularly
|
| 131 |
+
- Follow recommended crop rotation practices
|
| 132 |
+
""")
|
| 133 |
+
|
| 134 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
st.error(f"Prediction error: {str(e)}")
|
| 137 |
+
|
| 138 |
+
with tab2:
|
| 139 |
+
st.header("Machine Learning Project Steps")
|
| 140 |
+
st.write("""
|
| 141 |
+
This crop prediction system was developed following these key machine learning steps:
|
| 142 |
+
""")
|
| 143 |
+
|
| 144 |
+
steps = {
|
| 145 |
+
"1. Problem Definition π§ ": {
|
| 146 |
+
"description": "Identify the agricultural challenge and define objectives for crop prediction.",
|
| 147 |
+
"actions": [
|
| 148 |
+
"Determine key factors affecting crop growth",
|
| 149 |
+
"Define success metrics for the model"
|
| 150 |
+
]
|
| 151 |
+
},
|
| 152 |
+
"2. Data Collection π": {
|
| 153 |
+
"description": "Gather comprehensive agricultural datasets.",
|
| 154 |
+
"actions": [
|
| 155 |
+
"Collect soil nutrient data (N, P, K, pH)",
|
| 156 |
+
"Gather weather and climate data",
|
| 157 |
+
"Obtain historical crop yield information"
|
| 158 |
+
]
|
| 159 |
+
},
|
| 160 |
+
"3. Data Cleaning π§Ή": {
|
| 161 |
+
"description": "Prepare raw data for analysis by addressing quality issues.",
|
| 162 |
+
"actions": [
|
| 163 |
+
"Handle missing values and outliers",
|
| 164 |
+
"Correct measurement inconsistencies",
|
| 165 |
+
"Remove duplicate entries"
|
| 166 |
+
]
|
| 167 |
+
},
|
| 168 |
+
"4. Exploratory Analysis π": {
|
| 169 |
+
"description": "Understand data patterns and relationships.",
|
| 170 |
+
"actions": [
|
| 171 |
+
"Analyze feature distributions",
|
| 172 |
+
"Identify correlations between variables",
|
| 173 |
+
"Visualize data patterns"
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
"5. Feature Engineering βοΈ": {
|
| 177 |
+
"description": "Select and transform relevant features.",
|
| 178 |
+
"actions": [
|
| 179 |
+
"Normalize numerical features",
|
| 180 |
+
"Create derived features if needed",
|
| 181 |
+
"Select most predictive features"
|
| 182 |
+
]
|
| 183 |
+
},
|
| 184 |
+
"6. Model Selection π€": {
|
| 185 |
+
"description": "Choose appropriate machine learning algorithms.",
|
| 186 |
+
"actions": [
|
| 187 |
+
"Compare classification algorithms",
|
| 188 |
+
"Evaluate based on accuracy and performance",
|
| 189 |
+
"Select final model (Logistic Regression)"
|
| 190 |
+
]
|
| 191 |
+
},
|
| 192 |
+
"7. Model Training ποΈββοΈ": {
|
| 193 |
+
"description": "Train the selected model with prepared data.",
|
| 194 |
+
"actions": [
|
| 195 |
+
"Split data into training and validation sets",
|
| 196 |
+
"Train model with optimal parameters",
|
| 197 |
+
"Validate model performance"
|
| 198 |
+
]
|
| 199 |
+
},
|
| 200 |
+
"8. Model Evaluation π": {
|
| 201 |
+
"description": "Assess model performance rigorously.",
|
| 202 |
+
"actions": [
|
| 203 |
+
"Calculate precision, recall, and F1-score",
|
| 204 |
+
"Analyze confusion matrix",
|
| 205 |
+
"Test on unseen data"
|
| 206 |
+
]
|
| 207 |
+
},
|
| 208 |
+
"9. Deployment π": {
|
| 209 |
+
"description": "Implement the model in a production environment.",
|
| 210 |
+
"actions": [
|
| 211 |
+
"Develop user-friendly interface",
|
| 212 |
+
"Create API endpoints if needed",
|
| 213 |
+
"Ensure scalability"
|
| 214 |
+
]
|
| 215 |
+
},
|
| 216 |
+
"10. Monitoring π": {
|
| 217 |
+
"description": "Continuously track and improve the system.",
|
| 218 |
+
"actions": [
|
| 219 |
+
"Monitor prediction accuracy",
|
| 220 |
+
"Update model with new data",
|
| 221 |
+
"Address concept drift"
|
| 222 |
+
]
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
for step, content in steps.items():
|
| 227 |
+
with st.expander(step):
|
| 228 |
+
st.write(content["description"])
|
| 229 |
+
st.markdown("**Key Actions:**")
|
| 230 |
+
for action in content["actions"]:
|
| 231 |
+
st.markdown(f"- {action}")
|
| 232 |
+
|
| 233 |
+
st.markdown("---")
|
| 234 |
+
st.write("This application helps farmers make data-driven decisions for optimal crop selection.")
|
| 235 |
+
|
| 236 |
+
# Add footer
|
| 237 |
+
st.markdown("---")
|
| 238 |
+
st.markdown(
|
| 239 |
+
"""
|
| 240 |
+
<div style="text-align: center; color: #777; font-size: 0.9em;">
|
| 241 |
+
Agricultural Decision Support System β’ Powered by Machine Learning
|
| 242 |
+
</div>
|
| 243 |
+
""",
|
| 244 |
+
unsafe_allow_html=True
|
| 245 |
+
)
|