Upload 12 files
Browse filesFiles changed (12)
- ann_model.h5Added+3
- app.pyAdded+241
- crime_label_encoder.pklAdded+3
- crime_pca.pklAdded+3
- crime_scaler.pklAdded+3
- fraud_scaler.pklAdded+3
- label_encoder.pklAdded+3
- minmax_scaler.pklAdded+3
- random_forest_model.pklAdded+3
- requirements.txtAdded+9
- testing.ipynbAdded+256
- xgboost_model.pklAdded+3
123version https://git-lfs.github.com/spec/v1oid sha256:17320b7e764e7bff91445c843b061726d4798676a1cebc96aeb3540e9cb7a0ddsize 187840123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel, validatorimport pickleimport joblibimport numpy as npimport tensorflow as tfimport pandas as pd
app = FastAPI()
# Input validation using Pydanticclass HealthPredictionRequest(BaseModel): Gender: str Age: int SBP: int HBP: int heart_rate: int Glucose: int SpO2: int Temprature: float
@validator("Gender") def validate_gender(cls, value): if value not in ["M", "F"]: raise ValueError("Gender must be 'M' or 'F'.") return value
@validator("Age", "SBP", "HBP", "heart_rate", "Glucose", "SpO2") def validate_positive_integers(cls, value): if value <= 0: raise ValueError("Values must be positive integers.") return value
@validator("Temprature") def validate_temperature(cls, value): if value < 95.0 or value > 105.0: # Example temperature range raise ValueError("Temperature must be between 95.0 and 105.0.") return value
# Function to make predictionsdef get_prediction(Gender, Age, SBP, HBP, heart_rate, Glucose, SpO2, Temprature): # Load the scaler with open('minmax_scaler.pkl', 'rb') as file: scaler = pickle.load(file)
# Load the model model_path = 'random_forest_model.pkl' with open(model_path, 'rb') as file: model = joblib.load(file)
# Load the label encoder for Gender with open('label_encoder.pkl', 'rb') as file: label_encoder = pickle.load(file)
# Convert Gender to numeric Gender_encoded = label_encoder.transform([Gender])[0]
# Create input DataFrame input_data = pd.DataFrame( [[Gender_encoded, Age, SBP, HBP, heart_rate, Glucose, SpO2, Temprature]], columns=['Gender', 'Age', 'SBP ', 'HBP ', 'heart_rate ', 'Glucose ', 'SpO2', 'Temprature '] ) # Scale the input data input_data_scaled = scaler.transform(input_data)
# Make prediction prediction = model.predict(input_data_scaled)
# Map prediction to label label_map = { 0: 'healthy', 1: 'high BP', 2: 'low BP', 3: 'high sugar', 4: 'low sugar', 5: 'low oxygen', 6: 'high temperature', 7: 'heartbeat is high', 8: 'risk' }
return label_map[prediction[0]]
# Define the input data structure using Pydanticclass FraudInput(BaseModel): V1: float V2: float V3: float V4: float V5: float V6: float V7: float V8: float V9: float V10: float V11: float V12: float V13: float V14: float V15: float V16: float V17: float V18: float V19: float V20: float V21: float V22: float V23: float V24: float V25: float V26: float V27: float V28: float Amount: float
# Inference method for fraud detectiondef fraud_inference(features, scaler_path="fraud_scaler.pkl", model_path="ann_model.h5"): # Load scaler and model with open(scaler_path, "rb") as f: scaler = pickle.load(f)
ann_model_loaded = tf.keras.models.load_model(model_path)
# Scale features scaled_features = scaler.transform(features)
# Perform inference predictions = ann_model_loaded.predict(scaled_features) predicted_label = np.argmax(predictions, axis=-1)
if predicted_label[0] == 0: return 'Not Fraud' else: return 'Fraud'
class CrimeData(BaseModel): Case: str Block: str IUCR: int Primary_Type: str Description: str Location_Description: str FBI_Code: int Updated_On: str Location: str
def crime_inference(Case, Block, IUCR, Primary_Type, Description, Location_Description, FBI_Code, Updated_On, Location): # Load the scaler with open('crime_scaler.pkl', 'rb') as file: scaler = joblib.load(file)
# Load the model model_path = 'xgboost_model.pkl' with open(model_path, 'rb') as file: model = joblib.load(file)
# Load the PCA with open('crime_pca.pkl', 'rb') as file: pca = joblib.load(file)
with open('crime_label_encoder.pkl', 'rb') as file: label_encoder = joblib.load(file)
# Create input DataFrame input_data = pd.DataFrame( [[Case, Block, IUCR, Primary_Type, Description, Location_Description, FBI_Code, Updated_On, Location]], columns=['Case Number', 'Block', 'IUCR', 'Primary Type', 'Description', 'Location Description', 'FBI Code', 'Updated On', 'Location'] ) categorical_cols = ['Case Number', 'Block', 'IUCR', 'Primary Type', 'Description', 'Location Description', 'FBI Code', 'Updated On', 'Location']
# Label encoding for categorical columns for col in categorical_cols: input_data[col] = label_encoder.fit_transform(input_data[col])
# Scale the input data input_data_scaled = scaler.transform(input_data)
# Apply PCA transformation pca_features = pca.transform(input_data_scaled) print(pca_features.shape)
# Make prediction prediction = model.predict(pca_features)
# Map prediction to label label_map = {0: 'not arrest', 1: 'arrest'}
return label_map[prediction[0]]
# API endpoint@app.post("/health_predict")def predict(request: HealthPredictionRequest): try: # Call the prediction function result = get_prediction( Gender=request.Gender, Age=request.Age, SBP=request.SBP, HBP=request.HBP, heart_rate=request.heart_rate, Glucose=request.Glucose, SpO2=request.SpO2, Temprature=request.Temprature ) return {"prediction": result} except Exception as e: raise HTTPException(status_code=400, detail=str(e))
# Define an endpoint for prediction@app.post("/fraud_predict")async def predict(input_data: FraudInput): # Convert input data to DataFrame data_dict = input_data.dict() data = pd.DataFrame([data_dict])
# Call the fraud detection inference method label = fraud_inference(data) return {"prediction": label}
@app.post("/predict_crime")async def predict_crime(data: CrimeData): result = crime_inference( Case=data.Case, Block=data.Block, IUCR=data.IUCR, Primary_Type=data.Primary_Type, Description=data.Description, Location_Description=data.Location_Description, FBI_Code=data.FBI_Code, Updated_On=data.Updated_On, Location=data.Location ) return {"prediction": result}123version https://git-lfs.github.com/spec/v1oid sha256:0325378e0425ef32b16d7b7d306b70ce25a75125883719a0a4b58746f01ed11asize 4589444123version https://git-lfs.github.com/spec/v1oid sha256:0a4430a321d230159d330d03a6566a48f1386fd7dbe48deccb67175497d7d25bsize 1847123version https://git-lfs.github.com/spec/v1oid sha256:07ad0d7c1af4743e5d64d473b74f5f95844e9ac8ad963bc53ecbe98133157573size 1263123version https://git-lfs.github.com/spec/v1oid sha256:47e924aad2b34aa8493dc96fe951862c8ba4d85fc90feadcdb6ce3226c2be43dsize 1400123version https://git-lfs.github.com/spec/v1oid sha256:1455978add98562390b696dbf4d05a3a2b842a29322ceb47661d8322aae84fd1size 250123version https://git-lfs.github.com/spec/v1oid sha256:e73f82bfcb893cb2d56f4d7a216c491e22d6345d3345e6dfd76c7f04a6eeeb73size 964123version https://git-lfs.github.com/spec/v1oid sha256:246b6a4bb2629f21499f68bfd7f75b83073cf9ba80d75d0451658c7c3383f556size 9296289123456789Pillow==10.4.0fastapi==0.112.0uvicorn==0.30.5pydantic==2.8.2scikit-learn==1.6.0tensorflow==2.16.1pandas==2.2.0numpy==1.26.4joblib==1.3.2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256{ "cells": [ { "cell_type": "code", "execution_count": 8, "id": "initial_id", "metadata": { "collapsed": true, "ExecuteTime": { "end_time": "2025-01-11T19:07:39.073318726Z", "start_time": "2025-01-11T19:07:38.201074211Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Prediction Result: {'prediction': 'healthy'}\n" ] } ], "source": [ "import requests\n", "\n", "# Define the URL of the FastAPI endpoint\n", "url = \"http://127.0.0.1:8000/health_predict\" # Replace with the actual endpoint if hosted remotely\n", "\n", "# Define the input payload\n", "payload = {\n", " \"Gender\": \"M\",\n", " \"Age\": 67,\n", " \"SBP\": 145,\n", " \"HBP\": 84,\n", " \"heart_rate\": 116,\n", " \"Glucose\": 128,\n", " \"SpO2\": 98,\n", " \"Temprature\": 97.8\n", "}\n", "\n", "# Make the POST request\n", "response = requests.post(url, json=payload)\n", "\n", "# Print the response\n", "if response.status_code == 200:\n", " print(\"Prediction Result:\", response.json())\n", "else:\n", " print(f\"Error: {response.status_code}, Message: {response.text}\")\n" ] }, { "cell_type": "code", "execution_count": 9, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Prediction: Not Fraud\n" ] } ], "source": [ "import requests\n", "\n", "# URL of the FastAPI endpoint\n", "url = \"http://127.0.0.1:8000/fraud_predict\"\n", "\n", "# Sample data to send in the POST request (make sure the data format matches the model)\n", "input_data = {\n", " \"V1\": 0.1,\n", " \"V2\": 0.4,\n", " \"V3\": 0.7,\n", " \"V4\": 1.0,\n", " \"V5\": 1.3,\n", " \"V6\": 0.1,\n", " \"V7\": 0.4,\n", " \"V8\": 0.7,\n", " \"V9\": 1.0,\n", " \"V10\": 1.3,\n", " \"V11\": 0.1,\n", " \"V12\": 0.4,\n", " \"V13\": 0.7,\n", " \"V14\": 1.0,\n", " \"V15\": 1.3,\n", " \"V16\": 0.1,\n", " \"V17\": 0.4,\n", " \"V18\": 0.7,\n", " \"V19\": 1.0,\n", " \"V20\": 1.3,\n", " \"V21\": 0.1,\n", " \"V22\": 0.4,\n", " \"V23\": 0.7,\n", " \"V24\": 1.0,\n", " \"V25\": 1.3,\n", " \"V26\": 0.1,\n", " \"V27\": 0.4,\n", " \"V28\": 0.7,\n", " \"Amount\": 100\n", "}\n", "\n", "# Send the POST request to the FastAPI server\n", "response = requests.post(url, json=input_data)\n", "\n", "# Check if the request was successful and print the response\n", "if response.status_code == 200:\n", " result = response.json()\n", " print(\"Prediction:\", result[\"prediction\"])\n", "else:\n", " print(\"Error:\", response.status_code, response.text)\n" ], "metadata": { "collapsed": false, "ExecuteTime": { "end_time": "2025-01-11T19:11:14.154786492Z", "start_time": "2025-01-11T19:11:13.225551826Z" } }, "id": "39edb6c6f953f8df" }, { "cell_type": "code", "execution_count": 17, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Prediction Result: {'prediction': 'not arrest'}\n" ] } ], "source": [ "import requests\n", "\n", "# Sample data to send in the request\n", "sample_data = {\n", " \"Case\": \"JF113025\",\n", " \"Block\": \"067XX S MORGAN ST\",\n", " \"IUCR\": 2826,\n", " \"Primary_Type\": \"OTHER OFFENSE\",\n", " \"Description\": \"HARASSMENT BY ELECTRONIC MEANS\",\n", " \"Location_Description\": \"RESIDENCE\",\n", " \"FBI_Code\": 26,\n", " \"Updated_On\": \"9/14/2023 15:41\",\n", " \"Location\": \"(41.771782439, -87.649436929)\"\n", "}\n", "\n", "# URL for FastAPI endpoint\n", "url = \"http://127.0.0.1:8000/predict_crime\"\n", "\n", "# Send a POST request with the sample data as JSON\n", "response = requests.post(url, json=sample_data)\n", "\n", "# Check if the request was successful\n", "if response.status_code == 200:\n", " print(f\"Prediction Result: {response.json()}\")\n", "else:\n", " print(f\"Error: {response.status_code}, {response.text}\")\n" ], "metadata": { "collapsed": false, "ExecuteTime": { "end_time": "2025-01-11T19:44:26.136356206Z", "start_time": "2025-01-11T19:44:25.549072705Z" } }, "id": "be329568072d336c" }, { "cell_type": "code", "execution_count": 18, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "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", "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n", "2025-01-12 00:45:44.479984: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "fastapi version: 0.115.4\n", "pydantic version: 2.9.2\n", "pickle version: 4.0\n", "joblib version: 1.3.2\n", "numpy version: 1.26.4\n", "tensorflow version: 2.16.1\n", "pandas version: 2.2.0\n" ] } ], "source": [ "import fastapi\n", "import pydantic\n", "import pickle\n", "import joblib\n", "import numpy as np\n", "import tensorflow as tf\n", "import pandas as pd\n", "\n", "# Print the versions of each library\n", "print(f\"fastapi version: {fastapi.__version__}\")\n", "print(f\"pydantic version: {pydantic.__version__}\")\n", "print(f\"pickle version: {pickle.format_version}\") # pickle doesn't have __version__, but you can check the format version\n", "print(f\"joblib version: {joblib.__version__}\")\n", "print(f\"numpy version: {np.__version__}\")\n", "print(f\"tensorflow version: {tf.__version__}\")\n", "print(f\"pandas version: {pd.__version__}\")\n" ], "metadata": { "collapsed": false, "ExecuteTime": { "end_time": "2025-01-11T19:45:45.753678471Z", "start_time": "2025-01-11T19:45:42.265117643Z" } }, "id": "c76b855ced5fe0a3" }, { "cell_type": "code", "execution_count": null, "outputs": [], "source": [], "metadata": { "collapsed": false }, "id": "fc1962a8e8381309" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.6" } }, "nbformat": 4, "nbformat_minor": 5}123version https://git-lfs.github.com/spec/v1oid sha256:2d73d404228707d31e38583b40da2e6641b401b155b71f576c44386122ec5ccdsize 460774ann_model.h5Added+3
app.pyAdded+241
crime_label_encoder.pklAdded+3
crime_pca.pklAdded+3
crime_scaler.pklAdded+3
fraud_scaler.pklAdded+3
label_encoder.pklAdded+3
minmax_scaler.pklAdded+3
random_forest_model.pklAdded+3
requirements.txtAdded+9
testing.ipynbAdded+256
xgboost_model.pklAdded+3