Запрос интеграции Python JS (FastAPI) [дубликат]Python

Программы на Python
Anonymous
Запрос интеграции Python JS (FastAPI) [дубликат]

Сообщение Anonymous »

Код предназначен для получения информации о возрасте, поле и т. д. пользователя, чтобы спрогнозировать лучшую цену путем сравнения трех алгоритмов. у меня проблема с API между JS и Python. это не работает
модель запущена, ошибок нет, веб-сайт может читать, но не может серверная часть отправить лучшую стоимость во внешний интерфейс, должна появиться лучшая стоимость
на веб-сайте показано оптимальная стоимость и сохранение информации в базе данных 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) => {
event.preventDefault(); // Prevent the default form submission behavior
resultVisibility();
handleFormSubmit(event);
});

let currName = "setah";
welcomeName.innerText = currName;

function resultVisibility() {
result.style.display = "flex";
prophesyBtn.style.display = "none";
}
function handleFormSubmit(event) {
event.preventDefault();

const data = {
children: document.getElementById("children").value,
age: document.getElementById("age").value,
sex: parseInt(document.querySelector('input[name="sex"]:checked').value),
bmi: document.getElementById("Bmi").value,
region: parseInt(document.getElementById("region").value),
smoker: parseInt(document.querySelector('input[name="smoker"]:checked').value),
};

fetch("http://127.0.0.1:8000/prediction", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => {
if (response.ok) {
return response.json(); // Parse the response JSON
} else {
throw new Error("Request failed with status: " + response.status);
}
})
.then((responseData) => {
// Handle the response data
console.log(responseData);
})
.catch((error) =>  {
console.error(error);
});
}
машинное обучение Python

Код: Выделить всё

import pandas as pd
import pickle
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware

# Create the FastAPI app instance
app = FastAPI()

# Add CORS middleware
origins = [
"http://localhost",
"http://localhost:5500",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

# Load the dataset
df = pd.read_csv("model/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'].map({'southwest': 1, 'southeast': 2, 'northwest': 3, 'northeast': 4})

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)

# Save the models as pickle files
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)

# Define the predict endpoint
@app.post("/predict")
async def predict(request: Request):
"""
Predicts medical cost based on user input and returns the predicted cost.

Args:
request (Request): HTTP request containing input data.

Returns:
JSONResponse: JSON response with the predicted cost.
"""
input_data = await request.json()

data = {
'age': input_data.get('age'),
'sex': input_data.get('sex'),
'bmi': input_data.get('bmi'),
'children': input_data.get('children'),
'smoker': input_data.get('smoker'),
'region': input_data.get('region')
}

cust_df = pd.DataFrame(data, index=[0])

with open("linear_regression_model.pkl", "rb") as f:
linear_regression_model = pickle.load(f)

with open("svr_model.pkl", "rb") as f:
svr_model = pickle.load(f)

with open("decision_tree_model.pkl", "rb") as f:
decision_tree_model = pickle.load(f)

input_data_array = cust_df[['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, best_prediction = None, None

if linear_regression_prediction 

Подробнее здесь: [url]https://stackoverflow.com/questions/78407432/integration-python-js-fastapi-request[/url]

Вернуться в «Python»