Skip to content

Commit 6441fbc

Browse files
authored
Add files via upload
1 parent 36c4730 commit 6441fbc

File tree

9 files changed

+4031
-0
lines changed

9 files changed

+4031
-0
lines changed

Crop_Prediction_Project (1).ipynb

Lines changed: 3909 additions & 0 deletions
Large diffs are not rendered by default.

app.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import streamlit as st
2+
import pandas as pd
3+
import pickle
4+
# Load and cache your dataset
5+
@st.cache_data
6+
def load_dataset():
7+
# Replace 'your_dataset.csv' with your actual CSV file name
8+
df = pd.read_csv('Crop.csv') # Change this to your CSV file name
9+
return df
10+
# Load your trained model (adjust path as needed)
11+
@st.cache_data
12+
def load_model():
13+
# Replace with your actual model loading code
14+
return pickle.load(open('crop_model.pkl', 'rb'))
15+
# Load the dataset
16+
df = load_dataset()
17+
model = load_model()
18+
# Streamlit app
19+
st.title("🌾 Crop Prediction System")
20+
st.write("Enter the farming conditions to predict the best crop")
21+
# Optional: Show dataset info
22+
with st.sidebar:
23+
st.subheader("Dataset Information")
24+
st.write(f"Total samples: {len(df)}")
25+
st.write(f"Features: {list(df.columns)}")
26+
if st.checkbox("Show sample data"):
27+
st.dataframe(df.head())
28+
# Create input fields for features
29+
st.subheader("Enter Soil and Climate Conditions")
30+
col1, col2 = st.columns(2)
31+
with col1:
32+
nitrogen = st.number_input("Nitrogen (N)", min_value=0, max_value=300, value=50)
33+
phosphorus = st.number_input("Phosphorus (P)", min_value=0, max_value=300, value=50)
34+
potassium = st.number_input("Potassium (K)", min_value=0, max_value=300, value=50)
35+
with col2:
36+
temperature = st.number_input("Temperature (°C)", min_value=0.0, max_value=50.0, value=25.0)
37+
humidity = st.slider("Humidity (%)", 0, 100, 50)
38+
ph = st.slider("pH Level", 0.0, 14.0, 7.0)
39+
rainfall = st.number_input("Rainfall (mm)", min_value=0.0, max_value=500.0, value=100.0)
40+
# Prediction
41+
if st.button("🔮 Predict Best Crop", type="primary"):
42+
# Create input array for prediction
43+
features = [[nitrogen, phosphorus, potassium, temperature, humidity, ph, rainfall]]
44+
# Convert to DataFrame with correct column names (adjust based on your dataset)
45+
feature_names = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']
46+
input_df = pd.DataFrame(features, columns=feature_names)
47+
# Make prediction
48+
try:
49+
prediction = model.predict(input_df)
50+
# Display result
51+
st.success(f"🌱 Recommended Crop: **{prediction[0]}**")
52+
# Optional: Show prediction confidence if available
53+
if hasattr(model, 'predict_proba'):
54+
proba = model.predict_proba(input_df)
55+
confidence = max(proba[0]) * 100
56+
st.info(f"Prediction Confidence: {confidence:.1f}%")
57+
except Exception as e:
58+
st.error(f"Error making prediction: {str(e)}")
59+
st.info("Please check that your model file and input features are compatible")
60+
# Additional information
61+
st.markdown("---")
62+
st.subheader("About this System")
63+
st.write("This system uses machine learning to recommend the best crop based on soil nutrients and climate conditions.")

crop_model.pkl

3.38 MB
Binary file not shown.

crop_model.sav

18.8 KB
Binary file not shown.

crop_scaler.sav

757 Bytes
Binary file not shown.

label_encoder.pkl

466 Bytes
Binary file not shown.
2.41 MB
Binary file not shown.

tempCodeRunnerFile.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import streamlit as st
2+
import pandas as pd
3+
import pickle
4+
# Load and cache your dataset
5+
@st.cache_data
6+
def load_dataset():
7+
# Replace 'your_dataset.csv' with your actual CSV file name
8+
df = pd.read_csv('Crop.csv') # Change this to your CSV file name
9+
return df
10+
# Load your trained model (adjust path as needed)
11+
@st.cache_data
12+
def load_model():
13+
# Replace with your actual model loading code
14+
return pickle.load(open('crop_model.pkl', 'rb'))
15+
# Load the dataset
16+
df = load_dataset()
17+
model = load_model()
18+
# Streamlit app
19+
st.title("🌾 Crop Prediction System")
20+
st.write("Enter the farming conditions to predict the best crop")
21+
# Optional: Show dataset info
22+
with st.sidebar:
23+
st.subheader("Dataset Information")
24+
st.write(f"Total samples: {len(df)}")
25+
st.write(f"Features: {list(df.columns)}")
26+
if st.checkbox("Show sample data"):
27+
st.dataframe(df.head())
28+
# Create input fields for features

train_model.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import pandas as pd
2+
import pickle
3+
from sklearn.model_selection import train_test_split
4+
from sklearn.ensemble import RandomForestClassifier
5+
from sklearn.preprocessing import LabelEncoder
6+
7+
# Load data
8+
df = pd.read_csv('Crop.csv')
9+
10+
# Prepare features and target
11+
X = df.drop('label', axis=1) # Replace 'label' with your target column name
12+
y = df['label'] # Replace 'label' with your target column name
13+
14+
# Encode target if it's text
15+
le = LabelEncoder()
16+
y_encoded = le.fit_transform(y)
17+
18+
# Split data
19+
X_train, X_test, y_train, y_test = train_test_split(X, y_encoded, test_size=0.2, random_state=42)
20+
21+
# Train model
22+
model = RandomForestClassifier(n_estimators=100, random_state=42)
23+
model.fit(X_train, y_train)
24+
25+
# Save model
26+
pickle.dump(model, open('crop_model.pkl', 'wb'))
27+
28+
# Save label encoder for predictions
29+
pickle.dump(le, open('label_encoder.pkl', 'wb'))
30+
31+
print("Model created and saved successfully!")

0 commit comments

Comments
 (0)