Krishna-Vishista commited on
Commit
dda53b2
·
verified ·
1 Parent(s): df49323

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +51 -0
  2. kmeans_model.joblib +3 -0
  3. scaler_model.joblib +3 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import joblib
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ app = Flask(__name__)
7
+
8
+ # Load the pre-trained model and scaler
9
+ try:
10
+ kmeans_model = joblib.load("kmeans_model.joblib")
11
+ scaler_model = joblib.load("scaler_model.joblib")
12
+ print("Models loaded successfully!")
13
+ except Exception as e:
14
+ print(f"Error loading models: {e}")
15
+ kmeans_model = None
16
+ scaler_model = None
17
+
18
+ @app.route("/predict", methods=["POST"])
19
+ def predict():
20
+ if kmeans_model is None or scaler_model is None:
21
+ return jsonify({"error": "Model not loaded. Please check deployment logs."}), 500
22
+
23
+ data = request.get_json(force=True)
24
+
25
+ try:
26
+ # Extract features and ensure order
27
+ age = data.get("age")
28
+ annual_income = data.get("annual_income")
29
+ spending_score = data.get("spending_score")
30
+
31
+ if age is None or annual_income is None or spending_score is None:
32
+ return jsonify({"error": "Missing required input features (age, annual_income, spending_score)."}), 400
33
+
34
+ # Create a DataFrame for scaling
35
+ features_df = pd.DataFrame([[age, annual_income, spending_score]],
36
+ columns=['Age', 'Annual Income (k$)', 'Spending Score (1-100)'])
37
+
38
+ # Scale the input features using the loaded scaler
39
+ scaled_features = scaler_model.transform(features_df)
40
+
41
+ # Predict the cluster
42
+ prediction = kmeans_model.predict(scaled_features)
43
+ cluster_id = int(prediction[0]) # Convert numpy int to Python int
44
+
45
+ return jsonify({"cluster_id": cluster_id})
46
+
47
+ except Exception as e:
48
+ return jsonify({"error": str(e)}), 500
49
+
50
+ if __name__ == "__main__":
51
+ app.run(debug=True) # debug=True for local testing, set to False for deployment
kmeans_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b7e0e562d37c81f1cfe50337ceddf09e8c09121b22fc1420d89ad0c09f75e3a
3
+ size 222
scaler_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d18f1b357561d4920a50a1130f241c526119ba4a5502a1de1062576cf715c8e
3
+ size 129