Вот код для создания HTML-файла, позволяющего предсказать, есть ли у человека диабет или нет, с учетом этих 6 факторов: беременность, уровень глюкозы, кровяное давление, ИМТ, функция DiabetesPedigreeFunction и возраст.
Когда я запускаю HTML-файл , при запуске отображается ошибка, независимо от введенных данных. Есть ли этому причина и самое главное как это исправить? Любая помощь будет очень признательна.
from flask import Flask, request, jsonify
from flask_cors import CORS
import util
app = Flask(import_name=__name__)
CORS(app)
@app.route('/get_num_pregnancies', methods=['GET'])
def get_num_pregancies():
response = jsonify({
'Pregnancies': util.get_demographic_info()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
@app.route('/check_for_diabetes', methods=['POST'])
def check_for_diabetes():
try:
Pregnancies = int(request.form['Pregnancies'])
Glucose = int(request.form['Glucose'])
BloodPressure = int(request.form['BloodPressure'])
BMI = float(request.form['BMI'])
DiabetesPedigreeFunction = float(request.form['DiabetesPedigreeFunction'])
Age = int(request.form['Age'])
prediction = util.check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age)
response = jsonify({
'diabetes_prediction': prediction
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
except Exception as e:
response = jsonify({'error': str(e)})
response.headers.add('Access-Control-Allow-Origin', '*')
return response, 500
if __name__ == '__main__':
print('Starting Python Flask for Diabeties Prediction')
util.load_saved_artifacts()
app.run(debug=True)
import json
import pickle
import numpy as np
from sklearn.preprocessing import StandardScaler
__data_columns = None
__model = None
__scaler = None
def check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age):
global __model
global __data_columns
global __scaler
# Ensure the model and data columns are loaded
if __model is None or __data_columns is None or __scaler is None:
load_saved_artifacts()
# Create a numpy array for the input features
input_features = np.array([[Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age]])
# Scale the input features using the same scaler fitted during training
input_features_scaled = __scaler.transform(input_features)
# Predict the outcome
prediction = __model.predict(input_features_scaled)
return prediction[0]
def get_demographic_info():
return __data_columns[:1]
def load_saved_artifacts():
print('Loading saved artifacts ...start')
global __data_columns
global __model
global __scaler
# Load data columns and model
try:
with open('modeL-json', 'r') as f:
__data_columns = json.load(f)['data_columns']
except FileNotFoundError as e:
print(f"Error: {e}")
return
try:
with open('model-pickle', 'rb') as f:
__model = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return
# Load the scaler used during training
try:
with open('scaler-pickle', 'rb') as f:
__scaler = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return
print('Loading saved artifacts ...done')
if __name__ == '__main__':
load_saved_artifacts()
if __data_columns:
# Test the prediction function
prediction = check_for_diabetes(6, 148, 72, 33.6, 0.627, 50)
print(f"Prediction: {'Diabetic' if prediction == 1 else 'Non-Diabetic'}")
else:
print("Failed to load the data columns.")
function onClickedPredictDiabetes() {
console.log("Predict Diabetes button clicked");
var pregnancies = parseInt(document.getElementById("Pregnancies").value);
var glucose = parseInt(document.getElementById("Glucose").value);
var bloodPressure = parseInt(document.getElementById("BloodPressure").value);
var bmi = parseFloat(document.getElementById("BMI").value);
var diabetesPedigreeFunction = parseFloat(document.getElementById("DiabetesPedigreeFunction").value);
var age = parseInt(document.getElementById("Age").value);
// Update the URL as needed
var url = "http://127.0.0.1:5000/check_for_diabetes"; // Use this if you are running the server locally
$.post(url, {
Pregnancies: pregnancies,
Glucose: glucose,
BloodPressure: bloodPressure,
BMI: bmi,
DiabetesPedigreeFunction: diabetesPedigreeFunction,
Age: age
})
.done(function(data) {
var prediction = data.diabetes_prediction == 1 ? "Diabetic" : "Non-Diabetic";
document.getElementById("predictionResult").innerHTML = "Prediction: " + prediction;
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error:", textStatus, errorThrown); // Log the error for debugging
document.getElementById("predictionResult").innerHTML = "Prediction: Error predicting diabetes.";
});
}
// No need for onPageLoad function for this context
Diabetes Prediction
Diabetes Prediction Form
Pregnancies
Glucose
Blood Pressure
BMI
Diabetes Pedigree Function
Age
Predict Diabetes
Prediction:
Подробнее здесь: https://stackoverflow.com/questions/786 ... generating
Кнопка HTML-файла не генерируется ⇐ CSS
Разбираемся в CSS
1719881932
Anonymous
Вот код для создания HTML-файла, позволяющего предсказать, есть ли у человека диабет или нет, с учетом этих 6 факторов: беременность, уровень глюкозы, кровяное давление, ИМТ, функция DiabetesPedigreeFunction и возраст.
Когда я запускаю HTML-файл , при запуске отображается ошибка, независимо от введенных данных. Есть ли этому причина и самое главное как это исправить? Любая помощь будет очень признательна.
from flask import Flask, request, jsonify
from flask_cors import CORS
import util
app = Flask(import_name=__name__)
CORS(app)
@app.route('/get_num_pregnancies', methods=['GET'])
def get_num_pregancies():
response = jsonify({
'Pregnancies': util.get_demographic_info()
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
@app.route('/check_for_diabetes', methods=['POST'])
def check_for_diabetes():
try:
Pregnancies = int(request.form['Pregnancies'])
Glucose = int(request.form['Glucose'])
BloodPressure = int(request.form['BloodPressure'])
BMI = float(request.form['BMI'])
DiabetesPedigreeFunction = float(request.form['DiabetesPedigreeFunction'])
Age = int(request.form['Age'])
prediction = util.check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age)
response = jsonify({
'diabetes_prediction': prediction
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
except Exception as e:
response = jsonify({'error': str(e)})
response.headers.add('Access-Control-Allow-Origin', '*')
return response, 500
if __name__ == '__main__':
print('Starting Python Flask for Diabeties Prediction')
util.load_saved_artifacts()
app.run(debug=True)
import json
import pickle
import numpy as np
from sklearn.preprocessing import StandardScaler
__data_columns = None
__model = None
__scaler = None
def check_for_diabetes(Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age):
global __model
global __data_columns
global __scaler
# Ensure the model and data columns are loaded
if __model is None or __data_columns is None or __scaler is None:
load_saved_artifacts()
# Create a numpy array for the input features
input_features = np.array([[Pregnancies, Glucose, BloodPressure, BMI, DiabetesPedigreeFunction, Age]])
# Scale the input features using the same scaler fitted during training
input_features_scaled = __scaler.transform(input_features)
# Predict the outcome
prediction = __model.predict(input_features_scaled)
return prediction[0]
def get_demographic_info():
return __data_columns[:1]
def load_saved_artifacts():
print('Loading saved artifacts ...start')
global __data_columns
global __model
global __scaler
# Load data columns and model
try:
with open('modeL-json', 'r') as f:
__data_columns = json.load(f)['data_columns']
except FileNotFoundError as e:
print(f"Error: {e}")
return
try:
with open('model-pickle', 'rb') as f:
__model = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return
# Load the scaler used during training
try:
with open('scaler-pickle', 'rb') as f:
__scaler = pickle.load(f)
except FileNotFoundError as e:
print(f"Error: {e}")
return
print('Loading saved artifacts ...done')
if __name__ == '__main__':
load_saved_artifacts()
if __data_columns:
# Test the prediction function
prediction = check_for_diabetes(6, 148, 72, 33.6, 0.627, 50)
print(f"Prediction: {'Diabetic' if prediction == 1 else 'Non-Diabetic'}")
else:
print("Failed to load the data columns.")
function onClickedPredictDiabetes() {
console.log("Predict Diabetes button clicked");
var pregnancies = parseInt(document.getElementById("Pregnancies").value);
var glucose = parseInt(document.getElementById("Glucose").value);
var bloodPressure = parseInt(document.getElementById("BloodPressure").value);
var bmi = parseFloat(document.getElementById("BMI").value);
var diabetesPedigreeFunction = parseFloat(document.getElementById("DiabetesPedigreeFunction").value);
var age = parseInt(document.getElementById("Age").value);
// Update the URL as needed
var url = "http://127.0.0.1:5000/check_for_diabetes"; // Use this if you are running the server locally
$.post(url, {
Pregnancies: pregnancies,
Glucose: glucose,
BloodPressure: bloodPressure,
BMI: bmi,
DiabetesPedigreeFunction: diabetesPedigreeFunction,
Age: age
})
.done(function(data) {
var prediction = data.diabetes_prediction == 1 ? "Diabetic" : "Non-Diabetic";
document.getElementById("predictionResult").innerHTML = "Prediction: " + prediction;
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error:", textStatus, errorThrown); // Log the error for debugging
document.getElementById("predictionResult").innerHTML = "Prediction: Error predicting diabetes.";
});
}
// No need for onPageLoad function for this context
Diabetes Prediction
Diabetes Prediction Form
Pregnancies
Glucose
Blood Pressure
BMI
Diabetes Pedigree Function
Age
Predict Diabetes
Prediction:
Подробнее здесь: [url]https://stackoverflow.com/questions/78694578/html-file-button-not-generating[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия