hareeshkumarkb commited on
Commit
8dfd124
·
verified ·
1 Parent(s): 1fe6dfd

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import joblib
3
+ import numpy as np
4
+ import pandas as pd
5
+ import os
6
+
7
+ # Create a Flask application instance
8
+ app = Flask(__name__)
9
+
10
+ # Define the path to the serialized model file
11
+ model_filename = 'best_model.joblib'
12
+ model_path = os.path.join(os.path.dirname(__file__), model_filename)
13
+
14
+
15
+ # Load the serialized model
16
+ try:
17
+ loaded_model = joblib.load(model_path)
18
+ print(f"Model loaded successfully from '{model_path}'")
19
+ except Exception as e:
20
+ print(f"Error loading model: {e}")
21
+ loaded_model = None # Set model to None if loading fails
22
+
23
+ # Define the prediction endpoint
24
+ @app.route('/predict', methods=['POST'])
25
+ def predict():
26
+ if loaded_model is None:
27
+ return jsonify({'error': 'Model not loaded'}), 500
28
+
29
+ try:
30
+ # Get the data from the request
31
+ data = request.get_json()
32
+
33
+ # Convert the input data to a pandas DataFrame
34
+ # Assuming the input data is a list of dictionaries,
35
+ # where each dictionary represents a data point with features.
36
+ # The order of features should match the training data.
37
+ input_df = pd.DataFrame(data)
38
+
39
+ # NOTE: The preprocessor object is not available here.
40
+ # In a real deployment, you would also serialize and load the preprocessor
41
+ # or recreate it with the exact same steps and parameters.
42
+ # For this example, we'll assume the input is already preprocessed or
43
+ # we skip preprocessing for simplicity (not recommended for production).
44
+ # If preprocessing is needed, you would do:
45
+ # input_processed = loaded_preprocessor.transform(input_df)
46
+ # For this example, let's assume the input data is already in the expected
47
+ # format for the loaded model (which expects processed features).
48
+ # In a real scenario, ensure the input data format matches the training data.
49
+ # Assuming the input data is already preprocessed (e.g., one-hot encoded and scaled)
50
+ # and is in the form of a list of lists or a numpy array that can be
51
+ # converted to a format compatible with the loaded model's expected input shape.
52
+ # For simplicity in this example, we will assume the input JSON
53
+ # directly corresponds to the processed features expected by the model.
54
+ # In a real-world scenario, you would need to implement the preprocessing steps here
55
+ # using the serialized preprocessor or by recreating it.
56
+
57
+ # Convert input_df to numpy array or appropriate format if needed by the model
58
+ # Based on the training code, the model was trained on a processed numpy array
59
+ # We will assume the input data JSON is structured to represent this processed array.
60
+ # If the input JSON is raw data, you'll need the preprocessor here.
61
+ # For now, let's assume the input JSON data can be directly passed to predict
62
+ # if it's structured correctly as a list of lists or similar.
63
+ # A safer approach would be to expect raw data and use a loaded preprocessor.
64
+
65
+ # For now, let's assume the input data JSON is a list of dictionaries,
66
+ # and we convert it to a DataFrame and then to a numpy array for prediction
67
+ # if the model expects a numpy array.
68
+ # However, since the model was trained on X_processed which was a sparse matrix initially
69
+ # from the ColumnTransformer, direct conversion to a numpy array might lose sparsity
70
+ # or cause issues if the original preprocessor's output format is critical.
71
+ # A robust solution requires serializing and loading the preprocessor as well.
72
+
73
+ # Given the context of previous cells, X_processed was likely a numpy array after transformation.
74
+ # Let's assume the input JSON data can be directly used to create a numpy array
75
+ # with the correct number of features (34 in this case, based on X_processed shape).
76
+
77
+ # Example assuming input data is a list of lists matching the processed features shape
78
+ input_data_processed = np.array(data['features'])
79
+
80
+
81
+ # Make predictions
82
+ predictions = loaded_model.predict(input_data_processed)
83
+
84
+ # Convert predictions to a list
85
+ predictions_list = predictions.tolist()
86
+
87
+ # Return the predictions as a JSON response
88
+ return jsonify({'predictions': predictions_list})
89
+
90
+ except Exception as e:
91
+ return jsonify({'error': str(e)}), 400
92
+
93
+ # To run the Flask application (for local testing)
94
+ if __name__ == '__main__':
95
+ # For local testing, you can run:
96
+ # Ensure the model file is in the same directory or adjust the model_path
97
+ # app.run(debug=True)
98
+ pass