gkc55 commited on
Commit
bb8ef20
·
1 Parent(s): db37451

Fix model loading and prediction issues - working locally

Browse files
Files changed (1) hide show
  1. app.py +85 -24
app.py CHANGED
@@ -18,19 +18,65 @@ def utility_processor():
18
  return IMAGE_BASE_URL + path
19
  return dict(get_image_url=get_image_url, images=IMAGES)
20
 
21
- # Update model loading with error handling
22
  try:
23
- model = pickle.load(open('model.pkl', 'rb'))
24
- sc = pickle.load(open('standscaler.pkl', 'rb'))
25
- ms = pickle.load(open('minmaxscaler.pkl', 'rb'))
 
 
 
 
 
26
  except Exception as e:
27
  print(f"Error loading models: {e}")
28
- # Provide default/dummy models if loading fails
29
- from sklearn.ensemble import RandomForestClassifier
30
- model = RandomForestClassifier()
31
- from sklearn.preprocessing import StandardScaler, MinMaxScaler
32
- sc = StandardScaler()
33
- ms = MinMaxScaler()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  # Define routes
36
  @app.route('/')
@@ -48,6 +94,7 @@ def recommendation():
48
 
49
  if request.method == 'POST':
50
  try:
 
51
  N = float(request.form['Nitrogen'])
52
  P = float(request.form['Phosporus'])
53
  K = float(request.form['Potassium'])
@@ -56,27 +103,41 @@ def recommendation():
56
  ph = float(request.form['Ph'])
57
  rainfall = float(request.form['Rainfall'])
58
 
 
59
  feature_list = [N, P, K, temp, humidity, ph, rainfall]
60
  single_pred = np.array(feature_list).reshape(1, -1)
61
 
62
- scaled_features = ms.transform(single_pred)
63
- final_features = sc.transform(scaled_features)
64
- prediction = model.predict(final_features)
65
-
66
- crop_dict = {1: "Rice", 2: "Maize", 3: "Jute", 4: "Cotton", 5: "Coconut", 6: "Papaya", 7: "Orange",
67
- 8: "Apple", 9: "Muskmelon", 10: "Watermelon", 11: "Grapes", 12: "Mango", 13: "Banana",
68
- 14: "Pomegranate", 15: "Lentil", 16: "Blackgram", 17: "Mungbean", 18: "Mothbeans",
69
- 19: "Pigeonpeas", 20: "Kidneybeans", 21: "Chickpea", 22: "Coffee"}
 
 
 
 
 
70
 
71
- if prediction[0] in crop_dict:
72
- crop = crop_dict[prediction[0]]
73
- result = "{} is the best crop to be cultivated right there".format(crop)
74
- else:
75
- result = "Sorry, we could not determine the best crop to be cultivated with the provided data."
 
 
 
 
 
76
  except Exception as e:
 
77
  result = f"An error occurred: {str(e)}"
78
 
79
- return render_template('recommendation.html', result=result, N=N, P=P, K=K, temp=temp, humidity=humidity, ph=ph, rainfall=rainfall)
 
 
80
 
81
  if __name__ == "__main__":
82
  app.run(host="0.0.0.0", port=7860)
 
18
  return IMAGE_BASE_URL + path
19
  return dict(get_image_url=get_image_url, images=IMAGES)
20
 
21
+ # Load and prepare data for scalers
22
  try:
23
+ # Try to load the models first
24
+ with open('model.pkl', 'rb') as f:
25
+ model = pickle.load(f)
26
+ with open('standscaler.pkl', 'rb') as f:
27
+ sc = pickle.load(f)
28
+ with open('minmaxscaler.pkl', 'rb') as f:
29
+ ms = pickle.load(f)
30
+ print("Models loaded successfully")
31
  except Exception as e:
32
  print(f"Error loading models: {e}")
33
+ try:
34
+ # Load the dataset and fit scalers
35
+ data = pd.read_csv('Crop_recommendation.csv')
36
+ features = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']
37
+ X = data[features].values
38
+ y = data['label'].values
39
+
40
+ # Create and fit scalers with actual data
41
+ from sklearn.preprocessing import StandardScaler, MinMaxScaler
42
+ ms = MinMaxScaler()
43
+ ms.fit(X)
44
+
45
+ # Transform with MinMaxScaler first
46
+ X_minmax = ms.transform(X)
47
+
48
+ sc = StandardScaler()
49
+ sc.fit(X_minmax)
50
+
51
+ # Create and fit model with transformed data
52
+ from sklearn.ensemble import RandomForestClassifier
53
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
54
+ model.fit(sc.transform(X_minmax), y)
55
+ print("Models fitted successfully with dataset")
56
+
57
+ # Save the fitted models
58
+ with open('model.pkl', 'wb') as f:
59
+ pickle.dump(model, f)
60
+ with open('standscaler.pkl', 'wb') as f:
61
+ pickle.dump(sc, f)
62
+ with open('minmaxscaler.pkl', 'wb') as f:
63
+ pickle.dump(ms, f)
64
+
65
+ except Exception as e:
66
+ print(f"Error fitting models: {e}")
67
+ # Create and fit default scalers with sample data as fallback
68
+ sample_data = np.array([[90, 40, 40, 20, 80, 7, 200],
69
+ [20, 30, 10, 25, 60, 6, 100]])
70
+
71
+ ms = MinMaxScaler()
72
+ ms.fit(sample_data)
73
+
74
+ sc = StandardScaler()
75
+ sc.fit(sample_data)
76
+
77
+ model = RandomForestClassifier()
78
+ model.fit(sample_data, [1, 2])
79
+ print("Using default models")
80
 
81
  # Define routes
82
  @app.route('/')
 
94
 
95
  if request.method == 'POST':
96
  try:
97
+ # Get form data
98
  N = float(request.form['Nitrogen'])
99
  P = float(request.form['Phosporus'])
100
  K = float(request.form['Potassium'])
 
103
  ph = float(request.form['Ph'])
104
  rainfall = float(request.form['Rainfall'])
105
 
106
+ # Prepare features
107
  feature_list = [N, P, K, temp, humidity, ph, rainfall]
108
  single_pred = np.array(feature_list).reshape(1, -1)
109
 
110
+ # Scale features
111
+ try:
112
+ scaled_features = ms.transform(single_pred)
113
+ final_features = sc.transform(scaled_features)
114
+
115
+ # Make prediction
116
+ prediction = model.predict(final_features)
117
+
118
+ # Map prediction to crop name
119
+ crop_dict = {1: "Rice", 2: "Maize", 3: "Jute", 4: "Cotton", 5: "Coconut", 6: "Papaya", 7: "Orange",
120
+ 8: "Apple", 9: "Muskmelon", 10: "Watermelon", 11: "Grapes", 12: "Mango", 13: "Banana",
121
+ 14: "Pomegranate", 15: "Lentil", 16: "Blackgram", 17: "Mungbean", 18: "Mothbeans",
122
+ 19: "Pigeonpeas", 20: "Kidneybeans", 21: "Chickpea", 22: "Coffee"}
123
 
124
+ if prediction[0] in crop_dict:
125
+ crop = crop_dict[prediction[0]]
126
+ result = "{} is the best crop to be cultivated right there".format(crop)
127
+ else:
128
+ result = "Sorry, we could not determine the best crop to be cultivated with the provided data."
129
+
130
+ except Exception as e:
131
+ print(f"Error in prediction: {e}")
132
+ result = "An error occurred during prediction. Please try again."
133
+
134
  except Exception as e:
135
+ print(f"Error processing form data: {e}")
136
  result = f"An error occurred: {str(e)}"
137
 
138
+ return render_template('recommendation.html', result=result,
139
+ N=N, P=P, K=K, temp=temp,
140
+ humidity=humidity, ph=ph, rainfall=rainfall)
141
 
142
  if __name__ == "__main__":
143
  app.run(host="0.0.0.0", port=7860)