The code is about receiving information from the user’s age, gender, etc., in order to predict the best price through a comparison between the three algorithms. i have problem with API between JS and python.
it is not work
the website show the best cost and save information into database
JS
const predictionForm = document.getElementById("predictionForm");
const result = document.getElementById("result");
const amount = document.querySelectorAll("span");
let welcomeName = document.getElementById("name");
const prophesyBtn = document.getElementById("prophesyCost");
predictionForm.addEventListener("submit", (event) => {
resultVisibility();
handleFormSubmit(event);
});
// name of the user
let currName = "setah";
welcomeName.innerText = currName;
// Display the amount
currAmount = "10,459";
amount.forEach((el) => (el.innerText = currAmount));
// The prediction result visibility
function resultVisibility() {
result.style.display = "flex";
prophesyBtn.style.display = "none";
}
function handleFormSubmit(event) {
event.preventDefault(); // Prevent default form submission
// Access form data and build JSON object
const data = {
children: document.getElementById("children").value,
age: document.getElementById("age").value,
sex: document.getElementById("sex").value,
bmi: document.getElementById("bmi").value,
region: document.getElementById("region").value,
};
fetchPrediction(data);
fetch('model/Medical Insurance.py')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
}type here
python machine learning
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import sqlite3
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
import pickle
from sklearn.metrics import mean_squared_error
import tensorflow as tf
from tensorflow import keras
import os
app = FastAPI()
df = pd.read_csv("insurance.csv")
df['sex'] = df['sex'].apply(lambda x: 0 if x == 'male' else 1)
df['smoker'] = df['smoker'].apply(lambda x: 1 if x == 'yes' else 0)
df['region'] = df['region'].apply({'southwest': 1, 'southeast': 2, 'northwest': 3, 'northeast': 4}.get)
X = df[['age', 'sex', 'bmi', 'children', 'smoker', 'region']]
y = df['charges']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
linear_regression_model = LinearRegression()
svr_model = SVR()
decision_tree_model = DecisionTreeRegressor()
linear_regression_model.fit(X_train, y_train)
svr_model.fit(X_train, y_train)
decision_tree_model.fit(X_train, y_train)
linear_regression_predictions = linear_regression_model.predict(X_test)
svr_predictions = svr_model.predict(X_test)
decision_tree_predictions = decision_tree_model.predict(X_test)
model = keras.models.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(6,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae'])
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0)
with open('linear_regression_model.pkl', 'wb') as f:
pickle.dump(linear_regression_model, f)
with open('svr_model.pkl', 'wb') as f:
pickle.dump(svr_model, f)
with open('decision_tree_model.pkl', 'wb') as f:
pickle.dump(decision_tree_model, f)
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
data = {'age': 19, 'sex': 1, 'bmi': 27.9, 'children': 0, 'smoker': 1, 'region': 1}
cust_df = pd.DataFrame(data, index=[0])
cust_df = cust_df[['age', 'sex', 'bmi', 'children', 'smoker', 'region']]
cost_pred_linear_regression = linear_regression_model.predict(cust_df)
cost_pred_svr = svr_model.predict(cust_df)
cost_pred_decision_tree = decision_tree_model.predict(cust_df)
linear_regression_mse = mean_squared_error(y_test, linear_regression_predictions)
svr_mse = mean_squared_error(y_test, svr_predictions)
decision_tree_mse = mean_squared_error(y_test, decision_tree_predictions)
conn = sqlite3.connect('prediction.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS predictions
(age INTEGER, sex INTEGER, bmi float, children INTEGER, smoker INTEGER, region INTEGER,
linear_regression_prediction float, svr_prediction float, decision_tree_prediction float, best_model TEXT, email TEXT, name TEXT)''')
@app.post('/predict')
async def predict(request: Request):
input_data = await request.json()
if not all(key in input_data for key in ['age', 'sex', 'bmi', 'children', 'smoker', 'region', 'name', 'email']):
raise HTTPException(status_code=400, detail="Some keys are missing in the input data.")
age = input_data['age']
sex = input_data['sex']
bmi = input_data['bmi']
children = input_data['children']
smoker = input_data['smoker']
region = input_data['region']
name = input_data['name']
email = input_data['email']
input_data_array = np.array([[age, sex, bmi, children, smoker, region]])
linear_regression_prediction = linear_regression_model.predict(input_data_array)[0]
svr_prediction = svr_model.predict(input_data_array)[0]
decision_tree_prediction = decision_tree_model.predict(input_data_array)[0]
best_model = None
best_prediction = None
if linear_regression_mse <= svr_mse and linear_regression_mse <= decision_tree_mse:
best_model = 'Linear Regression'
best_prediction = linear_regression_model.predict(X_test)
elif svr_mse <= linear_regression_mse and svr_mse <= decision_tree_mse:
best_model = 'Support Vector Regression'
best_prediction = svr_model.predict(X_test)
else:
best_model = 'Decision Tree'
best_prediction = decision_tree_model.predict(X_test)
c.execute('''INSERT INTO predictions (age, sex, bmi, children, smoker, region,
linear_regression_prediction, svr_prediction, decision_tree_prediction, best_model, email, name)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(age, sex, bmi, children, smoker, region,
linear_regression_prediction, svr_prediction, decision_tree_prediction, best_model, email, name))
conn.commit()
return JSONResponse({'message': 'Prediction successfully recorded'})
if __name__ == '__main__':
origins = [
"http://localhost",
"http://localhost:8000",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)type here
main code
import pickle
import uvicorn
import numpy as np
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8000",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
with open("model/decision_tree_model.pkl", "rb") as f:
decision_tree_model = pickle.load(f)
with open("model/linear_regression_model.pkl", "rb") as f:
linear_regression_model = pickle.load(f)
with open("model/svr_model.pkl", "rb") as f:
svr_model = pickle.load(f)
@app.post("/predict")
async def predict(age: int, sex: int, bmi: float, children: int, smoker: int, region: int):
input_data_array = np.array([[age, sex, bmi, children, smoker, region]])
decision_tree_predicted_cost = decision_tree_model.predict(input_data_array)[0]
linear_regression_predicted_cost = linear_regression_model.predict(input_data_array)[0]
svr_predicted_cost = svr_model.predict(input_data_array)[0]
return JSONResponse({
"decision_tree_predicted_cost": round(decision_tree_predicted_cost, 2),
"linear_regression_predicted_cost": round(linear_regression_predicted_cost, 2),
"svr_predicted_cost": round(svr_predicted_cost, 2)
})
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)type here