-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_app.py
More file actions
2650 lines (2282 loc) · 118 KB
/
Copy pathsimple_app.py
File metadata and controls
2650 lines (2282 loc) · 118 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.model_selection import train_test_split, GridSearchCV, learning_curve, validation_curve
from sklearn.preprocessing import StandardScaler, MinMaxScaler, PolynomialFeatures
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from sklearn.metrics import roc_curve, auc, precision_recall_curve
from sklearn.cluster import KMeans, DBSCAN
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.inspection import permutation_importance
import joblib
import base64
from datetime import datetime
import time
# Set page configuration with dark theme
st.set_page_config(
page_title="AGROINTEL: Advanced Crop Recommendation System",
page_icon="🌱",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for sci-fi theme
st.markdown("""
<style>
/* Main background with gradient */
.main {
background: linear-gradient(to bottom right, #000428, #004e92);
color: #E0E0E0;
}
/* Sidebar styling */
.css-1d391kg {
background: linear-gradient(to bottom, #000428, #004e92);
}
/* Headers with sci-fi font and glow */
h1, h2, h3 {
font-family: 'Orbitron', sans-serif;
text-shadow: 0 0 10px rgba(0, 195, 255, 0.7);
}
/* Gradient text for titles */
.title-gradient {
background: -webkit-linear-gradient(#4facfe, #00f2fe);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-weight: bold;
}
/* Button styling */
.stButton>button {
background: linear-gradient(45deg, #0072ff, #00c6ff);
color: white;
border: none;
border-radius: 5px;
box-shadow: 0 0 15px rgba(0, 123, 255, 0.5);
transition: all 0.3s ease;
}
.stButton>button:hover {
box-shadow: 0 0 25px rgba(0, 123, 255, 0.8);
transform: translateY(-2px);
}
/* Card-like containers */
.css-1r6slb0 {
background: rgba(1, 10, 50, 0.7);
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0, 123, 255, 0.3);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* Dataframe styling */
.dataframe {
background: rgba(5, 15, 40, 0.85);
border-radius: 5px;
font-family: 'Courier New', monospace;
color: #00ff9d;
}
/* Success message styling */
.element-container div[data-testid="stImage"] {
border: 2px solid rgba(0, 255, 200, 0.3);
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 255, 200, 0.2);
}
/* Success message styling */
.element-container div[data-testid="stAlert"] {
background: rgba(13, 25, 47, 0.7);
border-radius: 10px;
border-left: 4px solid #00f2fe;
box-shadow: 0 0 15px rgba(0, 123, 255, 0.3);
}
/* Metric value styling */
.css-1v774eo {
font-family: 'Orbitron', sans-serif;
color: #00f2fe;
text-shadow: 0 0 10px rgba(0, 242, 254, 0.5);
}
/* Chart container styling */
div[data-testid="stDecoration"], div[data-testid="stDecoration"] div {
background: rgba(0, 20, 50, 0.6) !important;
border-radius: 10px;
border: 1px solid rgba(0, 123, 255, 0.3);
}
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
gap: 1px;
background-color: rgba(0, 20, 60, 0.5);
border-radius: 10px;
padding: 5px;
}
.stTabs [data-baseweb="tab"] {
background-color: rgba(0, 40, 100, 0.7);
border-radius: 8px;
color: #00f2fe;
padding: 5px 15px;
margin: 2px;
}
.stTabs [aria-selected="true"] {
background-color: rgba(0, 105, 225, 0.7);
}
/* Loader animation */
.stSpinner {
border-color: #00f2fe !important;
border-top-color: transparent !important;
}
</style>
<!-- Google Fonts for Orbitron (sci-fi font) -->
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
""", unsafe_allow_html=True)
# Page header with sci-fi style
st.markdown('<h1 class="title-gradient">AGROINTEL: Advanced Crop Recommendation System 🌱</h1>', unsafe_allow_html=True)
# Animated introduction text
def animate_text():
text = "Analyzing soil composition and environmental parameters to determine optimal crop selection..."
placeholder = st.empty()
for i in range(len(text) + 1):
placeholder.markdown(f"<p style='font-family: monospace; color: #00f2fe;'>{text[:i]}_</p>", unsafe_allow_html=True)
time.sleep(0.02)
placeholder.markdown(f"<p style='font-family: monospace; color: #00f2fe;'>{text}</p>", unsafe_allow_html=True)
# System status message
st.markdown("""
<div style="background-color: rgba(0,20,40,0.7); padding: 10px; border-radius: 5px;
border-left: 3px solid #00f2fe; margin-top: 20px; font-family: 'Courier New', monospace;">
<span style="color: #00f2fe;">●</span> <span style="color: #e0e0e0;">SYSTEM ACTIVE</span> |
<span style="color: #00f2fe;">●</span> <span style="color: #e0e0e0;">DATA NODES CONNECTED</span> |
<span style="color: #00f2fe;">●</span> <span style="color: #e0e0e0;">PREDICTION ENGINE READY</span>
</div>
""", unsafe_allow_html=True)
# Run animation on initial load
animate_text()
# Load data
@st.cache_data
def load_data():
df = pd.read_csv("data/Crop_recommendation.csv")
return df
try:
# Load the data
df = load_data()
# Navigation sidebar with sci-fi styling
st.sidebar.markdown('<h2 class="title-gradient">COMMAND CENTER</h2>', unsafe_allow_html=True)
# Add a system status indicator
current_time = datetime.now().strftime("%H:%M:%S")
st.sidebar.markdown(f"""
<div style="background-color: rgba(0,20,40,0.7); padding: 10px; border-radius: 5px; margin-bottom: 20px;
font-family: 'Courier New', monospace; font-size: 0.8em;">
<span style="color: #00f2fe;">SYSTEM TIME:</span> <span style="color: #e0e0e0;">{current_time}</span><br>
<span style="color: #00f2fe;">STATUS:</span> <span style="color: #00ff9d;">OPERATIONAL</span><br>
<span style="color: #00f2fe;">DATA INTEGRITY:</span> <span style="color: #00ff9d;">100%</span>
</div>
""", unsafe_allow_html=True)
# Add a divider
st.sidebar.markdown('<hr style="margin: 15px 0; border: 0; border-top: 1px solid rgba(0, 242, 254, 0.3);">', unsafe_allow_html=True)
# Navigation menu with icons and styled as a sci-fi console
st.sidebar.markdown('<div style="color: #00f2fe; margin-bottom: 10px;">SELECT MODULE:</div>', unsafe_allow_html=True)
page = st.sidebar.radio(
"",
["Home",
"Data Analysis",
"Model Performance",
"Prediction Tool",
"Advanced Analysis",
"Feature Engineering",
"Clustering Analysis"]
)
# Add visual indicators
st.sidebar.markdown(f"""
<div style="margin-top: 30px; background-color: rgba(0,25,50,0.7); padding: 10px; border-radius: 5px;">
<div style="font-family: 'Courier New', monospace; color: #00f2fe; font-size: 0.8em; margin-bottom: 5px;">SELECTED MODULE:</div>
<div style="font-family: 'Orbitron', sans-serif; color: #00ff9d; font-weight: bold;">{page.upper()}</div>
</div>
""", unsafe_allow_html=True)
# Add a futuristic help section
with st.sidebar.expander("SYSTEM DIAGNOSTICS"):
st.markdown("""
<div style="font-family: 'Courier New', monospace; color: #e0e0e0; font-size: 0.9em;">
<span style="color: #00f2fe;">></span> AI Models: <span style="color: #00ff9d;">OPTIMAL</span><br>
<span style="color: #00f2fe;">></span> Data Pipeline: <span style="color: #00ff9d;">ACTIVE</span><br>
<span style="color: #00f2fe;">></span> Neural Net: <span style="color: #00ff9d;">CALIBRATED</span><br>
<span style="color: #00f2fe;">></span> Memory Usage: <span style="color: #00ff9d;">42%</span>
</div>
""", unsafe_allow_html=True)
# Home Page
if page == "Home":
st.header("Welcome to the Crop Recommendation System")
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("Dataset Overview")
st.write(f"Number of samples: {df.shape[0]}")
st.write(f"Number of features: {df.shape[1]-1}") # Excluding the target column
st.write(f"Number of crop types: {df['label'].nunique()}")
st.subheader("Dataset Preview")
st.dataframe(df.head(10))
st.subheader("Statistical Summary")
st.dataframe(df.describe())
with col2:
st.subheader("Crop Distribution")
crop_counts = df['label'].value_counts().reset_index()
crop_counts.columns = ['Crop', 'Count']
fig = px.bar(
crop_counts,
x='Crop',
y='Count',
color='Crop',
title='Distribution of Crop Types in Dataset',
labels={'Count': 'Number of Samples', 'Crop': 'Crop Type'}
)
# Improve spacing for better readability
fig.update_layout(
margin=dict(l=80, r=40, t=80, b=120),
xaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14),
tickangle=45 # Angled labels to prevent overlap
),
yaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14)
)
)
st.plotly_chart(fig, use_container_width=True)
st.subheader("Features")
st.markdown("""
- **N**: Nitrogen content in soil (kg/ha)
- **P**: Phosphorus content in soil (kg/ha)
- **K**: Potassium content in soil (kg/ha)
- **temperature**: Temperature in degree Celsius
- **humidity**: Relative humidity in %
- **ph**: pH value of the soil
- **rainfall**: Rainfall in mm
""")
# Data Analysis Page
elif page == "Data Analysis":
st.header("Exploratory Data Analysis")
st.subheader("Feature Distributions")
# Create tabs for each type of feature
tabs = st.tabs(["Soil Nutrients (N, P, K)", "Environmental Factors"])
# Tab 1: Soil Nutrients
with tabs[0]:
fig = px.histogram(
df,
x=["N", "P", "K"],
facet_col="label",
facet_col_wrap=3,
histnorm='percent',
title="Distribution of Soil Nutrients by Crop Type",
labels={"value": "Nutrient Value (kg/ha)", "variable": "Nutrient Type"}
)
# Improve spacing for better readability of y-axis labels
fig.update_layout(
height=700, # Increased height for better spacing
margin=dict(l=80, r=40, t=80, b=40),
yaxis=dict(
tickfont=dict(size=10),
title_font=dict(size=12)
)
)
# Set uniform y-axis range and spacing for all facets
for i in range(len(fig.layout.annotations)):
fig.update_yaxes(
tickformat='.0%', # Format as percentage without decimal places
dtick=0.05, # Set tick interval to 5%
range=[0, 0.3], # Set consistent y-axis range
title_text="", # Remove redundant titles
tickfont=dict(size=10),
row=((i) // 3) + 1,
col=((i) % 3) + 1
)
st.plotly_chart(fig, use_container_width=True)
# Tab 2: Environmental Factors
with tabs[1]:
fig = px.histogram(
df,
x=["temperature", "humidity", "ph", "rainfall"],
facet_col="label",
facet_col_wrap=2,
histnorm='percent',
title="Distribution of Environmental Factors by Crop Type",
labels={"value": "Value", "variable": "Environmental Factor"}
)
# Improve spacing for better readability of y-axis labels
fig.update_layout(
height=800, # Increased height for better spacing
margin=dict(l=80, r=40, t=80, b=40),
yaxis=dict(
tickfont=dict(size=10),
title_font=dict(size=12)
)
)
# Set uniform y-axis range and spacing for all facets
for i in range(len(fig.layout.annotations)):
fig.update_yaxes(
tickformat='.0%', # Format as percentage without decimal places
dtick=0.05, # Set tick interval to 5%
range=[0, 0.3], # Set consistent y-axis range
title_text="", # Remove redundant titles
tickfont=dict(size=10),
row=((i) // 2) + 1, # Different layout from the first tab
col=((i) % 2) + 1
)
st.plotly_chart(fig, use_container_width=True)
st.subheader("Correlation Between Features")
# Calculate correlation matrix for features
feature_names = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']
corr = df[feature_names].corr()
# Create heatmap using plotly
fig = px.imshow(
corr,
text_auto=True,
aspect="auto",
color_continuous_scale='RdBu_r',
title="Feature Correlation Heatmap"
)
# Improve spacing for better readability
fig.update_layout(
height=500,
margin=dict(l=80, r=40, t=80, b=80),
xaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14)
),
yaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14)
)
)
st.plotly_chart(fig, use_container_width=True)
st.subheader("Soil Nutrient Analysis by Crop Type")
# Create 3D scatter plot
fig = px.scatter_3d(
df,
x='N',
y='P',
z='K',
color='label',
title='3D Distribution of Soil Nutrients by Crop Type',
labels={'N': 'Nitrogen (kg/ha)', 'P': 'Phosphorus (kg/ha)', 'K': 'Potassium (kg/ha)'},
opacity=0.7
)
# Update layout
fig.update_layout(
scene=dict(
xaxis_title='Nitrogen (N)',
yaxis_title='Phosphorus (P)',
zaxis_title='Potassium (K)'
),
height=700
)
st.plotly_chart(fig, use_container_width=True)
# Model Performance Page
elif page == "Model Performance":
st.header("Model Performance Analysis")
# Train and evaluate models
with st.spinner("Training and evaluating models..."):
# Extract features and target
X = df.drop('label', axis=1)
y = df['label']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train models
models = {
'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
'KNN': KNeighborsClassifier(n_neighbors=5),
'SVM': SVC(kernel='rbf', probability=True, random_state=42)
}
# Fit models
for name, model in models.items():
model.fit(X_train_scaled, y_train)
# Evaluate models
metrics = {}
for name, model in models.items():
y_pred = model.predict(X_test_scaled)
# Calculate metrics
metrics[name] = {
'accuracy': accuracy_score(y_test, y_pred),
'precision': precision_score(y_test, y_pred, average='weighted'),
'recall': recall_score(y_test, y_pred, average='weighted'),
'f1_score': f1_score(y_test, y_pred, average='weighted')
}
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("Performance Metrics")
# Create a DataFrame for comparison
comparison = pd.DataFrame(index=metrics.keys())
# Add metrics
comparison['Accuracy'] = [m['accuracy'] for m in metrics.values()]
comparison['Precision'] = [m['precision'] for m in metrics.values()]
comparison['Recall'] = [m['recall'] for m in metrics.values()]
comparison['F1 Score'] = [m['f1_score'] for m in metrics.values()]
# Format as percentages
for col in comparison.columns:
comparison[col] = comparison[col].map(lambda x: f"{x:.2%}")
# Display the table
st.table(comparison)
# Get feature importance from Random Forest
if 'Random Forest' in models:
st.subheader("Feature Importance")
# Get importance
importances = models['Random Forest'].feature_importances_
# Create DataFrame
importance_df = pd.DataFrame({
'Feature': X.columns,
'Importance': importances
}).sort_values('Importance', ascending=True)
# Plot
fig = px.bar(
importance_df,
x='Importance',
y='Feature',
orientation='h',
title='Feature Importance in Crop Prediction',
color='Importance',
color_continuous_scale='Viridis'
)
# Improve y-axis spacing for better readability
fig.update_layout(
height=400,
margin=dict(l=150, r=40, t=80, b=40),
yaxis=dict(
tickfont=dict(size=12),
tickmode='array',
tickvals=list(range(len(importance_df))),
ticktext=importance_df['Feature']
)
)
st.plotly_chart(fig, use_container_width=True)
with col2:
st.subheader("Model Selection")
st.write("""
Based on the performance metrics, the Random Forest model typically performs
best for this type of data due to its ability to capture non-linear relationships
and handle imbalanced classes.
""")
# Find best model
best_model = max(metrics.items(), key=lambda x: x[1]['accuracy'])[0]
st.success(f"Best performing model: {best_model}")
st.subheader("Best Model Settings")
if best_model == "Random Forest":
st.code("""
RandomForestClassifier(
n_estimators=100,
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
bootstrap=True,
random_state=42
)
""")
elif best_model == "KNN":
st.code("""
KNeighborsClassifier(
n_neighbors=5,
weights='uniform',
algorithm='auto',
leaf_size=30,
p=2,
metric='minkowski'
)
""")
else: # SVM
st.code("""
SVC(
C=1.0,
kernel='rbf',
degree=3,
gamma='scale',
probability=True,
random_state=42
)
""")
# Prediction Tool Page
elif page == "Prediction Tool":
st.header("Crop Recommendation Prediction Tool")
st.write("Enter your soil and environmental parameters to get a crop recommendation:")
col1, col2 = st.columns(2)
with col1:
N = st.number_input("Nitrogen (N) content in soil (kg/ha)", min_value=0, max_value=150, value=90)
P = st.number_input("Phosphorus (P) content in soil (kg/ha)", min_value=0, max_value=150, value=40)
K = st.number_input("Potassium (K) content in soil (kg/ha)", min_value=0, max_value=150, value=40)
temperature = st.number_input("Temperature (°C)", min_value=0.0, max_value=50.0, value=25.0)
with col2:
humidity = st.number_input("Humidity (%)", min_value=0.0, max_value=100.0, value=80.0)
ph = st.number_input("pH level", min_value=0.0, max_value=14.0, value=6.5)
rainfall = st.number_input("Rainfall (mm)", min_value=0.0, max_value=300.0, value=200.0)
# Model choice
model_choice = st.selectbox(
"Select prediction model",
["Random Forest", "KNN", "SVM"],
index=0
)
if st.button("Predict Crop"):
# Train the selected model
with st.spinner("Training model and generating prediction..."):
# Extract features and target
X = df.drop('label', axis=1)
y = df['label']
# Get unique crop names
crop_names = sorted(y.unique())
# Split the data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Scale features
scaler = StandardScaler()
scaler.fit(X_train)
# Select model
if model_choice == "Random Forest":
model = RandomForestClassifier(n_estimators=100, random_state=42)
elif model_choice == "KNN":
model = KNeighborsClassifier(n_neighbors=5)
else: # SVM
model = SVC(kernel='rbf', probability=True, random_state=42)
# Train model
model.fit(scaler.transform(X_train), y_train)
# Create input data
input_data = pd.DataFrame({
'N': [N], 'P': [P], 'K': [K],
'temperature': [temperature], 'humidity': [humidity],
'ph': [ph], 'rainfall': [rainfall]
})
# Scale input
input_scaled = scaler.transform(input_data)
# Make prediction
prediction = model.predict(input_scaled)[0]
probabilities = model.predict_proba(input_scaled)[0]
# Show prediction
st.success(f"Recommended crop: **{prediction}**")
# Provide interpretation
crop_data = df[df['label'] == prediction]
avg_values = crop_data.mean()
# Compare input values with typical values for this crop
comparisons = []
for feature in input_data.columns:
input_val = input_data[feature].iloc[0]
avg_val = avg_values[feature]
# Calculate the percentage difference
if avg_val != 0:
diff_pct = (input_val - avg_val) / avg_val * 100
# Determine if the value is within a typical range
if abs(diff_pct) <= 10:
status = "optimal"
elif abs(diff_pct) <= 25:
status = "acceptable" if diff_pct > 0 else "slightly low"
else:
status = "high" if diff_pct > 0 else "low"
comparisons.append(f"{feature.capitalize()}: Your value ({input_val:.2f}) is {status} compared to typical values ({avg_val:.2f})")
# Create interpretation text
interpretation = f"""
### Crop Recommendation Analysis
Based on your soil and environmental parameters, **{prediction}** is the recommended crop.
#### Comparison with Typical Values:
{" ".join([f"- {comp}" for comp in comparisons])}
#### Key Requirements for {prediction}:
- Soil fertility with {'high' if avg_values['N'] > 80 else 'moderate'} nitrogen content
- {'High' if avg_values['P'] > 80 else 'Moderate'} phosphorus levels
- {'High' if avg_values['K'] > 80 else 'Moderate'} potassium levels
- Temperature range around {avg_values['temperature']:.1f}°C
- Humidity levels around {avg_values['humidity']:.1f}%
- Soil pH around {avg_values['ph']:.1f}
- Annual rainfall around {avg_values['rainfall']:.1f} mm
"""
st.info(interpretation)
# Show probabilities for top crops
st.subheader("Crop Suitability Scores")
proba_df = pd.DataFrame({
'Crop': crop_names,
'Probability': probabilities
}).sort_values('Probability', ascending=False)
fig = px.bar(proba_df.head(5), x='Crop', y='Probability', color='Probability',
color_continuous_scale='Viridis', title='Top 5 Suitable Crops')
# Improve spacing for better readability
fig.update_layout(
height=400,
margin=dict(l=80, r=40, t=80, b=120),
xaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14),
tickangle=45 # Angled labels to prevent overlap
),
yaxis=dict(
tickfont=dict(size=12),
title_font=dict(size=14)
)
)
st.plotly_chart(fig)
# If Random Forest, show feature importance
if model_choice == "Random Forest":
st.subheader("Feature Importance for This Prediction")
st.write("""
This chart shows how each factor influenced the prediction.
Higher values indicate more important features for this specific recommendation.
""")
# Get feature importance
importances = model.feature_importances_
# Create DataFrame
importance_df = pd.DataFrame({
'Feature': input_data.columns,
'Importance': importances
}).sort_values('Importance', ascending=False)
# Plot
fig = px.bar(
importance_df,
x='Importance',
y='Feature',
orientation='h',
title='Feature Importance for Crop Prediction',
color='Importance',
color_continuous_scale='Viridis'
)
# Improve y-axis spacing for better readability
fig.update_layout(
height=400,
margin=dict(l=150, r=40, t=80, b=40),
yaxis=dict(
tickfont=dict(size=12),
tickmode='array',
tickvals=list(range(len(importance_df))),
ticktext=importance_df['Feature']
)
)
st.plotly_chart(fig)
# Add Feature Engineering page
elif page == "Feature Engineering":
st.markdown('<h1 class="title-gradient">Advanced Feature Engineering</h1>', unsafe_allow_html=True)
# Create a pulsing animation effect for "processing" status
st.markdown("""
<style>
@keyframes pulse {
0% { opacity: 0.6; }
50% { opacity: 1; }
100% { opacity: 0.6; }
}
.pulse {
animation: pulse 1.5s infinite ease-in-out;
}
</style>
<div style="background-color: rgba(0,40,80,0.7); padding: 15px; border-radius: 10px;
margin-bottom: 20px; border: 1px solid rgba(0, 242, 254, 0.3);">
<div style="display: flex; align-items: center;">
<span class="pulse" style="color: #00f2fe; margin-right: 10px;">●</span>
<span style="font-family: 'Courier New', monospace; color: #e0e0e0;">
QUANTUM FEATURE PROCESSOR ACTIVE
</span>
</div>
</div>
""", unsafe_allow_html=True)
# Create tabs for different feature engineering methods
tabs = st.tabs([
"Polynomial Features",
"Feature Ratios",
"PCA Transformation",
"Feature Selection"
])
# Extract features
X = df.drop('label', axis=1)
y = df['label']
feature_names = X.columns.tolist()
# Tab 1: Polynomial Features
with tabs[0]:
st.subheader("Polynomial Feature Generation")
st.markdown("""
<div style="font-family: 'Courier New', monospace; color: #e0e0e0; background-color: rgba(0,20,40,0.7);
padding: 10px; border-radius: 5px; border-left: 3px solid #00f2fe;">
Polynomial features create new features by calculating products and powers of the original features,
capturing non-linear relationships and interactions between variables.
</div>
""", unsafe_allow_html=True)
# Controls
degree = st.slider("Polynomial Degree", min_value=2, max_value=3, value=2)
poly_sample_size = st.slider("Sample Size for Visualization", min_value=100, max_value=1000, value=500)
# Process
with st.spinner("Generating polynomial features..."):
# Create polynomial features
poly = PolynomialFeatures(degree=degree, include_bias=False)
X_poly = poly.fit_transform(X)
# Get feature names
if hasattr(poly, 'get_feature_names_out'):
poly_feature_names = poly.get_feature_names_out(X.columns)
else:
# For older scikit-learn versions
poly_feature_names = poly.get_feature_names(X.columns)
# Create DataFrame with polynomial features
X_poly_df = pd.DataFrame(X_poly, columns=poly_feature_names)
# Display stats
st.markdown(f"""
<div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
<div style="background-color: rgba(0,30,60,0.7); padding: 15px; border-radius: 5px; flex: 1; margin-right: 10px;">
<h4 style="color: #00f2fe; margin: 0;">Original Features</h4>
<p style="font-family: 'Orbitron', sans-serif; font-size: 24px; color: #00ff9d; margin: 5px 0;">
{X.shape[1]}
</p>
</div>
<div style="background-color: rgba(0,30,60,0.7); padding: 15px; border-radius: 5px; flex: 1; margin-left: 10px;">
<h4 style="color: #00f2fe; margin: 0;">Polynomial Features</h4>
<p style="font-family: 'Orbitron', sans-serif; font-size: 24px; color: #00ff9d; margin: 5px 0;">
{X_poly.shape[1]}
</p>
</div>
</div>
""", unsafe_allow_html=True)
# Show sample of polynomial features
st.subheader("Sample of Generated Features")
st.dataframe(X_poly_df.head(10))
# Show correlation heatmap for selected polynomial features
st.subheader("Correlation Between Original and Polynomial Features")
# Select subset of polynomial features to avoid overwhelming visualization
selected_poly_features = list(X.columns) + list(X_poly_df.columns[X.shape[1]:X.shape[1]+5])
# Calculate correlation
corr_poly = X_poly_df[selected_poly_features].corr()
# Create heatmap
fig = px.imshow(
corr_poly,
color_continuous_scale='inferno',
title="Feature Correlation Heatmap"
)
fig.update_layout(height=600)
st.plotly_chart(fig, use_container_width=True)
# Feature importance for polynomial features
st.subheader("Polynomial Feature Importance")
# Sample data for faster processing
indices = np.random.choice(len(X), min(poly_sample_size, len(X)), replace=False)
X_poly_sample = X_poly[indices]
y_sample = y.iloc[indices]
# Train a quick Random Forest to get feature importance
rf_poly = RandomForestClassifier(n_estimators=50, max_depth=10, random_state=42)
rf_poly.fit(X_poly_sample, y_sample)
# Get importance
importances_poly = rf_poly.feature_importances_
# Create DataFrame for top 15 features
importance_poly_df = pd.DataFrame({
'Feature': poly_feature_names,
'Importance': importances_poly
}).sort_values('Importance', ascending=False).head(15)
# Plot
fig = px.bar(
importance_poly_df,
x='Importance',
y='Feature',
orientation='h',
title='Top 15 Polynomial Feature Importance',
color='Importance',
color_continuous_scale='plasma'
)
# Improve y-axis spacing for better readability
fig.update_layout(
height=500,
margin=dict(l=180, r=40, t=80, b=40),
yaxis=dict(
tickfont=dict(size=12),
tickmode='array',
tickvals=list(range(len(importance_poly_df))),
ticktext=importance_poly_df['Feature']
)
)
st.plotly_chart(fig, use_container_width=True)
# Tab 2: Feature Ratios
with tabs[1]:
st.subheader("Feature Ratio Analysis")
st.markdown("""
<div style="font-family: 'Courier New', monospace; color: #e0e0e0; background-color: rgba(0,20,40,0.7);
padding: 10px; border-radius: 5px; border-left: 3px solid #00f2fe;">
Ratio features capture relationships between pairs of features, which can be particularly useful
when the relative proportions between features are more important than their absolute values.
</div>
""", unsafe_allow_html=True)
# Feature selection for ratios
selected_features = st.multiselect(
"Select features to create ratios from:",
options=feature_names,
default=["N", "P", "K", "rainfall"]
)
if len(selected_features) >= 2:
with st.spinner("Calculating feature ratios..."):
# Create ratio features
ratio_features = []
X_ratio = X.copy()
for i, feat1 in enumerate(selected_features):
for feat2 in selected_features[i+1:]:
# Create ratio names
ratio_name1 = f"{feat1}_to_{feat2}"
ratio_name2 = f"{feat2}_to_{feat1}"
# Calculate ratios (handling division by zero)
X_ratio[ratio_name1] = X[feat1] / (X[feat2] + 1e-6)
X_ratio[ratio_name2] = X[feat2] / (X[feat1] + 1e-6)
ratio_features.extend([ratio_name1, ratio_name2])
# Display stats
st.markdown(f"""
<div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
<div style="background-color: rgba(0,30,60,0.7); padding: 15px; border-radius: 5px; flex: 1; margin-right: 10px;">
<h4 style="color: #00f2fe; margin: 0;">Original Features</h4>
<p style="font-family: 'Orbitron', sans-serif; font-size: 24px; color: #00ff9d; margin: 5px 0;">
{X.shape[1]}
</p>
</div>
<div style="background-color: rgba(0,30,60,0.7); padding: 15px; border-radius: 5px; flex: 1; margin-left: 10px;">
<h4 style="color: #00f2fe; margin: 0;">Ratio Features Created</h4>
<p style="font-family: 'Orbitron', sans-serif; font-size: 24px; color: #00ff9d; margin: 5px 0;">
{len(ratio_features)}
</p>
</div>
</div>
""", unsafe_allow_html=True)
# Show sample of ratio features
st.subheader("Sample of Ratio Features")
st.dataframe(X_ratio[ratio_features].head(10))
# Analyze correlation between ratio features and target
st.subheader("Correlation Between Ratio Features and Crop Types")
# One-hot encode the target
y_dummies = pd.get_dummies(y, prefix='crop')
# Combine ratio features and target dummies
ratio_with_target = pd.concat([X_ratio[ratio_features], y_dummies], axis=1)
# Calculate correlations
crop_cols = [col for col in ratio_with_target.columns if col.startswith('crop_')]
ratio_crop_corr = ratio_with_target.corr().loc[ratio_features, crop_cols]
# Create heatmap
fig = px.imshow(
ratio_crop_corr,
color_continuous_scale='RdBu_r',
title="Correlation Between Ratio Features and Crop Types"
)
fig.update_layout(height=600)
st.plotly_chart(fig, use_container_width=True)
# Visualize distributions of top ratio features
st.subheader("Distribution of Top Ratio Features by Crop")
# Find top ratio features based on correlation with any crop
abs_corr = np.abs(ratio_crop_corr.values)
top_ratios_idx = np.unravel_index(np.argsort(abs_corr, axis=None)[-5:], abs_corr.shape)
top_ratio_features = [ratio_features[i] for i in top_ratios_idx[0]]