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