-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrop_prediction.py
185 lines (135 loc) · 4.57 KB
/
crop_prediction.py
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
# -*- coding: utf-8 -*-
"""crop_prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ciQ49ohhHAZssJOd9FcX2_EcRoUYIG6X
## Imports
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import pickle
from sklearn.metrics import classification_report, accuracy_score
print("imported")
"""## Data"""
df = pd.read_csv("Crop_recommendation.csv")
df.head()
df.dtypes
df["label"].unique()
df["label"].value_counts()
features = df[["N", "P", "K", "temperature", "humidity", "ph", "rainfall"]]
target = df["label"]
features.head()
target.head()
Xtrain, Xtest, Ytrain, Ytest = train_test_split(
features, target, test_size=0.2, random_state=2
)
"""# Decision Tree
"""
from sklearn.tree import DecisionTreeClassifier
DecisionTree = DecisionTreeClassifier(criterion="entropy", random_state=2, max_depth=7)
DecisionTree.fit(Xtrain, Ytrain)
predicted_values = DecisionTree.predict(Xtest)
x = accuracy_score(Ytest, predicted_values)
print(x)
# Dump the trained Naive Bayes classifier with Pickle
DT_pkl_filename = "content/models/DecisionTree.pkl"
# Open the file to save as pkl file
DT_Model_pkl = open(DT_pkl_filename, "wb")
pickle.dump(DecisionTree, DT_Model_pkl)
# Close the pickle instances
DT_Model_pkl.close()
"""# Random Forest"""
from sklearn.ensemble import RandomForestClassifier
RandomForest = RandomForestClassifier(n_estimators=10, max_depth=7, random_state=0)
RandomForest.fit(Xtrain, Ytrain)
predicted_values = RandomForest.predict(Xtest)
x = accuracy_score(Ytest, predicted_values)
print(x)
# Dump the trained Random Forest with Pickle
RF_pkl_filename = "content/models/RandomForest.pkl"
# Open the file to save as pkl file
RF_Model_pkl = open(RF_pkl_filename, "wb")
pickle.dump(RandomForest, RF_Model_pkl)
# Close the pickle instances
RF_Model_pkl.close()
"""# Naive Bayes classifier"""
from sklearn.naive_bayes import GaussianNB
NaiveBayes = GaussianNB()
NaiveBayes.fit(Xtrain, Ytrain)
predicted_values = NaiveBayes.predict(Xtrain)
x = accuracy_score(Ytrain, predicted_values)
print(x)
# Dump the trained Naive Bayes classifier with Pickle
NB_pkl_filename = "content/models/NaiveBayes.pkl"
# Open the file to save as pkl file
NB_Model_pkl = open(NB_pkl_filename, "wb")
pickle.dump(NaiveBayes, NB_Model_pkl)
# Close the pickle instances
NB_Model_pkl.close()
"""# SVM"""
from sklearn.svm import SVC
# data normalization with sklearn
from sklearn.preprocessing import MinMaxScaler
# fit scaler on training data
norm = MinMaxScaler().fit(Xtrain)
X_train_norm = norm.transform(Xtrain)
# transform testing dataabs
X_test_norm = norm.transform(Xtest)
SVM = SVC(kernel="poly", degree=3, C=1)
SVM.fit(X_train_norm, Ytrain)
predicted_values = SVM.predict(X_test_norm)
x = accuracy_score(Ytest, predicted_values)
print(x)
# Dump the trained Naive Bayes classifier with Pickle
SVM_pkl_filename = "content/models/SVM.pkl"
# Open the file to save as pkl file
SVM_Model_pkl = open(SVM_pkl_filename, "wb")
pickle.dump(SVM, SVM_Model_pkl)
# Close the pickle instances
SVM_Model_pkl.close()
# print(predict(data))
# # Dependencies
# from flask import Flask, request, jsonify
# import joblib
# import traceback
# import pandas as pd
# import numpy as np
# import sys
# # Your API definition
# app = Flask(__name__)
# @app.route('/predict', methods=['POST'])
# def predict():
# if lr:
# try:
# json_ = request.json
# print(json_)
# query = pd.get_dummies(pd.DataFrame(json_))
# # query = query.reindex(columns=model_columns, fill_value=0)
# prediction = list(lr.predict(query))
# return jsonify({'prediction': str(prediction)})
# except:
# return jsonify({'trace': traceback.format_exc()})
# else:
# print ('Train the model first')
# return ('No model here to use')
# if __name__ == '__main__':
# try:
# port = int(sys.argv[1]) # This is for a command-line input
# except:
# port = 12345 # If you don't provide any port the port will be set to 12345
# lr = joblib.load('content/models/DecisionTree.pkl') # Load "model.pkl"
# print ('Model loaded')
# # model_columns = joblib.load("model_columns.pkl") # Load "model_columns.pkl"
# print ('Model columns loaded')
# app.run(port=port, debug=True)
from flask import Flask, request
# from sklearn.externals import joblib
import joblib
app = Flask(__name__)
@app.route("/")
def predict():
return "Hello world"
if __name__ == "__main__":
app.run(port=8082, debug=True)
# print(predict(data))