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("""
""", 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("
๐พ Smart Crop Prediction
", 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("", 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("
", 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("", 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"
{prediction[0]}
",
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("", 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(
"""
Agricultural Decision Support System โข Powered by Machine Learning
""",
unsafe_allow_html=True
)