muhammadhasnain100 commited on
Commit
27dbc11
·
verified ·
1 Parent(s): fe9bd64

Upload 12 files

Browse files
ann_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17320b7e764e7bff91445c843b061726d4798676a1cebc96aeb3540e9cb7a0dd
3
+ size 187840
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel, validator
3
+ import pickle
4
+ import joblib
5
+ import numpy as np
6
+ import tensorflow as tf
7
+ import pandas as pd
8
+
9
+ app = FastAPI()
10
+
11
+ # Input validation using Pydantic
12
+ class HealthPredictionRequest(BaseModel):
13
+ Gender: str
14
+ Age: int
15
+ SBP: int
16
+ HBP: int
17
+ heart_rate: int
18
+ Glucose: int
19
+ SpO2: int
20
+ Temprature: float
21
+
22
+ @validator("Gender")
23
+ def validate_gender(cls, value):
24
+ if value not in ["M", "F"]:
25
+ raise ValueError("Gender must be 'M' or 'F'.")
26
+ return value
27
+
28
+ @validator("Age", "SBP", "HBP", "heart_rate", "Glucose", "SpO2")
29
+ def validate_positive_integers(cls, value):
30
+ if value <= 0:
31
+ raise ValueError("Values must be positive integers.")
32
+ return value
33
+
34
+ @validator("Temprature")
35
+ def validate_temperature(cls, value):
36
+ if value < 95.0 or value > 105.0: # Example temperature range
37
+ raise ValueError("Temperature must be between 95.0 and 105.0.")
38
+ return value
39
+
40
+ # Function to make predictions
41
+ def get_prediction(Gender, Age, SBP, HBP, heart_rate, Glucose, SpO2, Temprature):
42
+ # Load the scaler
43
+ with open('minmax_scaler.pkl', 'rb') as file:
44
+ scaler = pickle.load(file)
45
+
46
+ # Load the model
47
+ model_path = 'random_forest_model.pkl'
48
+ with open(model_path, 'rb') as file:
49
+ model = joblib.load(file)
50
+
51
+ # Load the label encoder for Gender
52
+ with open('label_encoder.pkl', 'rb') as file:
53
+ label_encoder = pickle.load(file)
54
+
55
+ # Convert Gender to numeric
56
+ Gender_encoded = label_encoder.transform([Gender])[0]
57
+
58
+ # Create input DataFrame
59
+ input_data = pd.DataFrame(
60
+ [[Gender_encoded, Age, SBP, HBP, heart_rate, Glucose, SpO2, Temprature]],
61
+ columns=['Gender', 'Age', 'SBP ', 'HBP ', 'heart_rate ', 'Glucose ', 'SpO2', 'Temprature ']
62
+ )
63
+ # Scale the input data
64
+ input_data_scaled = scaler.transform(input_data)
65
+
66
+ # Make prediction
67
+ prediction = model.predict(input_data_scaled)
68
+
69
+ # Map prediction to label
70
+ label_map = {
71
+ 0: 'healthy',
72
+ 1: 'high BP',
73
+ 2: 'low BP',
74
+ 3: 'high sugar',
75
+ 4: 'low sugar',
76
+ 5: 'low oxygen',
77
+ 6: 'high temperature',
78
+ 7: 'heartbeat is high',
79
+ 8: 'risk'
80
+ }
81
+
82
+ return label_map[prediction[0]]
83
+
84
+
85
+
86
+ # Define the input data structure using Pydantic
87
+ class FraudInput(BaseModel):
88
+ V1: float
89
+ V2: float
90
+ V3: float
91
+ V4: float
92
+ V5: float
93
+ V6: float
94
+ V7: float
95
+ V8: float
96
+ V9: float
97
+ V10: float
98
+ V11: float
99
+ V12: float
100
+ V13: float
101
+ V14: float
102
+ V15: float
103
+ V16: float
104
+ V17: float
105
+ V18: float
106
+ V19: float
107
+ V20: float
108
+ V21: float
109
+ V22: float
110
+ V23: float
111
+ V24: float
112
+ V25: float
113
+ V26: float
114
+ V27: float
115
+ V28: float
116
+ Amount: float
117
+
118
+
119
+ # Inference method for fraud detection
120
+ def fraud_inference(features, scaler_path="fraud_scaler.pkl", model_path="ann_model.h5"):
121
+ # Load scaler and model
122
+ with open(scaler_path, "rb") as f:
123
+ scaler = pickle.load(f)
124
+
125
+ ann_model_loaded = tf.keras.models.load_model(model_path)
126
+
127
+ # Scale features
128
+ scaled_features = scaler.transform(features)
129
+
130
+ # Perform inference
131
+ predictions = ann_model_loaded.predict(scaled_features)
132
+ predicted_label = np.argmax(predictions, axis=-1)
133
+
134
+ if predicted_label[0] == 0:
135
+ return 'Not Fraud'
136
+ else:
137
+ return 'Fraud'
138
+
139
+ class CrimeData(BaseModel):
140
+ Case: str
141
+ Block: str
142
+ IUCR: int
143
+ Primary_Type: str
144
+ Description: str
145
+ Location_Description: str
146
+ FBI_Code: int
147
+ Updated_On: str
148
+ Location: str
149
+
150
+ def crime_inference(Case, Block, IUCR, Primary_Type, Description, Location_Description, FBI_Code, Updated_On, Location):
151
+ # Load the scaler
152
+ with open('crime_scaler.pkl', 'rb') as file:
153
+ scaler = joblib.load(file)
154
+
155
+ # Load the model
156
+ model_path = 'xgboost_model.pkl'
157
+ with open(model_path, 'rb') as file:
158
+ model = joblib.load(file)
159
+
160
+ # Load the PCA
161
+ with open('crime_pca.pkl', 'rb') as file:
162
+ pca = joblib.load(file)
163
+
164
+ with open('crime_label_encoder.pkl', 'rb') as file:
165
+ label_encoder = joblib.load(file)
166
+
167
+ # Create input DataFrame
168
+ input_data = pd.DataFrame(
169
+ [[Case, Block, IUCR, Primary_Type, Description, Location_Description, FBI_Code, Updated_On, Location]],
170
+ columns=['Case Number', 'Block', 'IUCR', 'Primary Type', 'Description', 'Location Description', 'FBI Code',
171
+ 'Updated On', 'Location']
172
+ )
173
+ categorical_cols = ['Case Number', 'Block', 'IUCR', 'Primary Type', 'Description',
174
+ 'Location Description', 'FBI Code', 'Updated On', 'Location']
175
+
176
+ # Label encoding for categorical columns
177
+ for col in categorical_cols:
178
+ input_data[col] = label_encoder.fit_transform(input_data[col])
179
+
180
+ # Scale the input data
181
+ input_data_scaled = scaler.transform(input_data)
182
+
183
+ # Apply PCA transformation
184
+ pca_features = pca.transform(input_data_scaled)
185
+ print(pca_features.shape)
186
+
187
+
188
+ # Make prediction
189
+ prediction = model.predict(pca_features)
190
+
191
+ # Map prediction to label
192
+ label_map = {0: 'not arrest', 1: 'arrest'}
193
+
194
+ return label_map[prediction[0]]
195
+
196
+ # API endpoint
197
+ @app.post("/health_predict")
198
+ def predict(request: HealthPredictionRequest):
199
+ try:
200
+ # Call the prediction function
201
+ result = get_prediction(
202
+ Gender=request.Gender,
203
+ Age=request.Age,
204
+ SBP=request.SBP,
205
+ HBP=request.HBP,
206
+ heart_rate=request.heart_rate,
207
+ Glucose=request.Glucose,
208
+ SpO2=request.SpO2,
209
+ Temprature=request.Temprature
210
+ )
211
+ return {"prediction": result}
212
+ except Exception as e:
213
+ raise HTTPException(status_code=400, detail=str(e))
214
+
215
+
216
+
217
+ # Define an endpoint for prediction
218
+ @app.post("/fraud_predict")
219
+ async def predict(input_data: FraudInput):
220
+ # Convert input data to DataFrame
221
+ data_dict = input_data.dict()
222
+ data = pd.DataFrame([data_dict])
223
+
224
+ # Call the fraud detection inference method
225
+ label = fraud_inference(data)
226
+ return {"prediction": label}
227
+
228
+ @app.post("/predict_crime")
229
+ async def predict_crime(data: CrimeData):
230
+ result = crime_inference(
231
+ Case=data.Case,
232
+ Block=data.Block,
233
+ IUCR=data.IUCR,
234
+ Primary_Type=data.Primary_Type,
235
+ Description=data.Description,
236
+ Location_Description=data.Location_Description,
237
+ FBI_Code=data.FBI_Code,
238
+ Updated_On=data.Updated_On,
239
+ Location=data.Location
240
+ )
241
+ return {"prediction": result}
crime_label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0325378e0425ef32b16d7b7d306b70ce25a75125883719a0a4b58746f01ed11a
3
+ size 4589444
crime_pca.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a4430a321d230159d330d03a6566a48f1386fd7dbe48deccb67175497d7d25b
3
+ size 1847
crime_scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07ad0d7c1af4743e5d64d473b74f5f95844e9ac8ad963bc53ecbe98133157573
3
+ size 1263
fraud_scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47e924aad2b34aa8493dc96fe951862c8ba4d85fc90feadcdb6ce3226c2be43d
3
+ size 1400
label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1455978add98562390b696dbf4d05a3a2b842a29322ceb47661d8322aae84fd1
3
+ size 250
minmax_scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e73f82bfcb893cb2d56f4d7a216c491e22d6345d3345e6dfd76c7f04a6eeeb73
3
+ size 964
random_forest_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:246b6a4bb2629f21499f68bfd7f75b83073cf9ba80d75d0451658c7c3383f556
3
+ size 9296289
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Pillow==10.4.0
2
+ fastapi==0.112.0
3
+ uvicorn==0.30.5
4
+ pydantic==2.8.2
5
+ scikit-learn==1.6.0
6
+ tensorflow==2.16.1
7
+ pandas==2.2.0
8
+ numpy==1.26.4
9
+ joblib==1.3.2
testing.ipynb ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 8,
6
+ "id": "initial_id",
7
+ "metadata": {
8
+ "collapsed": true,
9
+ "ExecuteTime": {
10
+ "end_time": "2025-01-11T19:07:39.073318726Z",
11
+ "start_time": "2025-01-11T19:07:38.201074211Z"
12
+ }
13
+ },
14
+ "outputs": [
15
+ {
16
+ "name": "stdout",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "Prediction Result: {'prediction': 'healthy'}\n"
20
+ ]
21
+ }
22
+ ],
23
+ "source": [
24
+ "import requests\n",
25
+ "\n",
26
+ "# Define the URL of the FastAPI endpoint\n",
27
+ "url = \"http://127.0.0.1:8000/health_predict\" # Replace with the actual endpoint if hosted remotely\n",
28
+ "\n",
29
+ "# Define the input payload\n",
30
+ "payload = {\n",
31
+ " \"Gender\": \"M\",\n",
32
+ " \"Age\": 67,\n",
33
+ " \"SBP\": 145,\n",
34
+ " \"HBP\": 84,\n",
35
+ " \"heart_rate\": 116,\n",
36
+ " \"Glucose\": 128,\n",
37
+ " \"SpO2\": 98,\n",
38
+ " \"Temprature\": 97.8\n",
39
+ "}\n",
40
+ "\n",
41
+ "# Make the POST request\n",
42
+ "response = requests.post(url, json=payload)\n",
43
+ "\n",
44
+ "# Print the response\n",
45
+ "if response.status_code == 200:\n",
46
+ " print(\"Prediction Result:\", response.json())\n",
47
+ "else:\n",
48
+ " print(f\"Error: {response.status_code}, Message: {response.text}\")\n"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": 9,
54
+ "outputs": [
55
+ {
56
+ "name": "stdout",
57
+ "output_type": "stream",
58
+ "text": [
59
+ "Prediction: Not Fraud\n"
60
+ ]
61
+ }
62
+ ],
63
+ "source": [
64
+ "import requests\n",
65
+ "\n",
66
+ "# URL of the FastAPI endpoint\n",
67
+ "url = \"http://127.0.0.1:8000/fraud_predict\"\n",
68
+ "\n",
69
+ "# Sample data to send in the POST request (make sure the data format matches the model)\n",
70
+ "input_data = {\n",
71
+ " \"V1\": 0.1,\n",
72
+ " \"V2\": 0.4,\n",
73
+ " \"V3\": 0.7,\n",
74
+ " \"V4\": 1.0,\n",
75
+ " \"V5\": 1.3,\n",
76
+ " \"V6\": 0.1,\n",
77
+ " \"V7\": 0.4,\n",
78
+ " \"V8\": 0.7,\n",
79
+ " \"V9\": 1.0,\n",
80
+ " \"V10\": 1.3,\n",
81
+ " \"V11\": 0.1,\n",
82
+ " \"V12\": 0.4,\n",
83
+ " \"V13\": 0.7,\n",
84
+ " \"V14\": 1.0,\n",
85
+ " \"V15\": 1.3,\n",
86
+ " \"V16\": 0.1,\n",
87
+ " \"V17\": 0.4,\n",
88
+ " \"V18\": 0.7,\n",
89
+ " \"V19\": 1.0,\n",
90
+ " \"V20\": 1.3,\n",
91
+ " \"V21\": 0.1,\n",
92
+ " \"V22\": 0.4,\n",
93
+ " \"V23\": 0.7,\n",
94
+ " \"V24\": 1.0,\n",
95
+ " \"V25\": 1.3,\n",
96
+ " \"V26\": 0.1,\n",
97
+ " \"V27\": 0.4,\n",
98
+ " \"V28\": 0.7,\n",
99
+ " \"Amount\": 100\n",
100
+ "}\n",
101
+ "\n",
102
+ "# Send the POST request to the FastAPI server\n",
103
+ "response = requests.post(url, json=input_data)\n",
104
+ "\n",
105
+ "# Check if the request was successful and print the response\n",
106
+ "if response.status_code == 200:\n",
107
+ " result = response.json()\n",
108
+ " print(\"Prediction:\", result[\"prediction\"])\n",
109
+ "else:\n",
110
+ " print(\"Error:\", response.status_code, response.text)\n"
111
+ ],
112
+ "metadata": {
113
+ "collapsed": false,
114
+ "ExecuteTime": {
115
+ "end_time": "2025-01-11T19:11:14.154786492Z",
116
+ "start_time": "2025-01-11T19:11:13.225551826Z"
117
+ }
118
+ },
119
+ "id": "39edb6c6f953f8df"
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": 17,
124
+ "outputs": [
125
+ {
126
+ "name": "stdout",
127
+ "output_type": "stream",
128
+ "text": [
129
+ "Prediction Result: {'prediction': 'not arrest'}\n"
130
+ ]
131
+ }
132
+ ],
133
+ "source": [
134
+ "import requests\n",
135
+ "\n",
136
+ "# Sample data to send in the request\n",
137
+ "sample_data = {\n",
138
+ " \"Case\": \"JF113025\",\n",
139
+ " \"Block\": \"067XX S MORGAN ST\",\n",
140
+ " \"IUCR\": 2826,\n",
141
+ " \"Primary_Type\": \"OTHER OFFENSE\",\n",
142
+ " \"Description\": \"HARASSMENT BY ELECTRONIC MEANS\",\n",
143
+ " \"Location_Description\": \"RESIDENCE\",\n",
144
+ " \"FBI_Code\": 26,\n",
145
+ " \"Updated_On\": \"9/14/2023 15:41\",\n",
146
+ " \"Location\": \"(41.771782439, -87.649436929)\"\n",
147
+ "}\n",
148
+ "\n",
149
+ "# URL for FastAPI endpoint\n",
150
+ "url = \"http://127.0.0.1:8000/predict_crime\"\n",
151
+ "\n",
152
+ "# Send a POST request with the sample data as JSON\n",
153
+ "response = requests.post(url, json=sample_data)\n",
154
+ "\n",
155
+ "# Check if the request was successful\n",
156
+ "if response.status_code == 200:\n",
157
+ " print(f\"Prediction Result: {response.json()}\")\n",
158
+ "else:\n",
159
+ " print(f\"Error: {response.status_code}, {response.text}\")\n"
160
+ ],
161
+ "metadata": {
162
+ "collapsed": false,
163
+ "ExecuteTime": {
164
+ "end_time": "2025-01-11T19:44:26.136356206Z",
165
+ "start_time": "2025-01-11T19:44:25.549072705Z"
166
+ }
167
+ },
168
+ "id": "be329568072d336c"
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": 18,
173
+ "outputs": [
174
+ {
175
+ "name": "stderr",
176
+ "output_type": "stream",
177
+ "text": [
178
+ "2025-01-12 00:45:43.425294: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
179
+ "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
180
+ "2025-01-12 00:45:44.479984: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n"
181
+ ]
182
+ },
183
+ {
184
+ "name": "stdout",
185
+ "output_type": "stream",
186
+ "text": [
187
+ "fastapi version: 0.115.4\n",
188
+ "pydantic version: 2.9.2\n",
189
+ "pickle version: 4.0\n",
190
+ "joblib version: 1.3.2\n",
191
+ "numpy version: 1.26.4\n",
192
+ "tensorflow version: 2.16.1\n",
193
+ "pandas version: 2.2.0\n"
194
+ ]
195
+ }
196
+ ],
197
+ "source": [
198
+ "import fastapi\n",
199
+ "import pydantic\n",
200
+ "import pickle\n",
201
+ "import joblib\n",
202
+ "import numpy as np\n",
203
+ "import tensorflow as tf\n",
204
+ "import pandas as pd\n",
205
+ "\n",
206
+ "# Print the versions of each library\n",
207
+ "print(f\"fastapi version: {fastapi.__version__}\")\n",
208
+ "print(f\"pydantic version: {pydantic.__version__}\")\n",
209
+ "print(f\"pickle version: {pickle.format_version}\") # pickle doesn't have __version__, but you can check the format version\n",
210
+ "print(f\"joblib version: {joblib.__version__}\")\n",
211
+ "print(f\"numpy version: {np.__version__}\")\n",
212
+ "print(f\"tensorflow version: {tf.__version__}\")\n",
213
+ "print(f\"pandas version: {pd.__version__}\")\n"
214
+ ],
215
+ "metadata": {
216
+ "collapsed": false,
217
+ "ExecuteTime": {
218
+ "end_time": "2025-01-11T19:45:45.753678471Z",
219
+ "start_time": "2025-01-11T19:45:42.265117643Z"
220
+ }
221
+ },
222
+ "id": "c76b855ced5fe0a3"
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "execution_count": null,
227
+ "outputs": [],
228
+ "source": [],
229
+ "metadata": {
230
+ "collapsed": false
231
+ },
232
+ "id": "fc1962a8e8381309"
233
+ }
234
+ ],
235
+ "metadata": {
236
+ "kernelspec": {
237
+ "display_name": "Python 3",
238
+ "language": "python",
239
+ "name": "python3"
240
+ },
241
+ "language_info": {
242
+ "codemirror_mode": {
243
+ "name": "ipython",
244
+ "version": 2
245
+ },
246
+ "file_extension": ".py",
247
+ "mimetype": "text/x-python",
248
+ "name": "python",
249
+ "nbconvert_exporter": "python",
250
+ "pygments_lexer": "ipython2",
251
+ "version": "2.7.6"
252
+ }
253
+ },
254
+ "nbformat": 4,
255
+ "nbformat_minor": 5
256
+ }
xgboost_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d73d404228707d31e38583b40da2e6641b401b155b71f576c44386122ec5ccd
3
+ size 460774