-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
45 lines (39 loc) · 1.57 KB
/
Copy pathapp.py
File metadata and controls
45 lines (39 loc) · 1.57 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
from flask import Flask, request, jsonify, render_template
import pickle, numpy as np, os
app = Flask(__name__)
if not os.path.exists("model.pkl"):
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
with open("model.pkl", "wb") as f:
pickle.dump(model, f)
print("Model trained and saved!")
else:
with open("model.pkl", "rb") as f:
model = pickle.load(f)
print("Model loaded!")
@app.route("/")
def home():
return render_template("index.html")
@app.route("/predict", methods=["POST"])
def predict():
try:
data = request.get_json()
features = np.array([[data["sepal_length"], data["sepal_width"], data["petal_length"], data["petal_width"]]])
pred = model.predict(features)[0]
probs = model.predict_proba(features)[0]
conf = round(max(probs) * 100, 2)
species = {0: "Setosa", 1: "Versicolor", 2: "Virginica"}[pred]
return jsonify({"species": species, "confidence": conf, "prediction": int(pred)})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/health")
def health():
return jsonify({"status": "healthy"})
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port, debug=False)