import gradio as gr import joblib import tensorflow as tf from tensorflow.keras.models import load_model import os import pandas as pd os.environ["KERAS_BACKEND"] = "jax" import keras loaded_model = keras.models.load_model('loan_approval_model1.keras') loaded_preprocessor = joblib.load('preprocessor1.pkl') def predict_loan_approval( Age, AnnualIncome, CreditScore, EmploymentStatus, EducationLevel, Experience, LoanAmount, LoanDuration, MaritalStatus, HomeOwnershipStatus, MonthlyDebtPayments, CreditCardUtilizationRate, NumberOfOpenCreditLines,BankruptcyHistory, LoanPurpose, PreviousLoanDefaults, PaymentHistory, LengthOfCreditHistory, SavingsAccountBalance, CheckingAccountBalance, TotalAssets, TotalLiabilities, MonthlyIncome, JobTenure, NetWorth, MonthlyLoanPayment,RiskScore ): input_data = pd.DataFrame({ 'Age': [Age], 'AnnualIncome': [AnnualIncome], 'CreditScore': [CreditScore], 'EmploymentStatus': [EmploymentStatus], 'EducationLevel': [EducationLevel], 'Experience': [Experience], 'LoanAmount': [LoanAmount], 'LoanDuration': [LoanDuration], 'MaritalStatus': [MaritalStatus], 'HomeOwnershipStatus': [HomeOwnershipStatus], 'MonthlyDebtPayments': [MonthlyDebtPayments], 'CreditCardUtilizationRate': [CreditCardUtilizationRate], 'NumberOfOpenCreditLines': [NumberOfOpenCreditLines], 'BankruptcyHistory': [BankruptcyHistory], 'LoanPurpose': [LoanPurpose], 'PreviousLoanDefaults': [PreviousLoanDefaults], 'PaymentHistory': [PaymentHistory], 'LengthOfCreditHistory': [LengthOfCreditHistory], 'SavingsAccountBalance': [SavingsAccountBalance], 'CheckingAccountBalance': [CheckingAccountBalance], 'TotalAssets': [TotalAssets], 'TotalLiabilities': [TotalLiabilities], 'MonthlyIncome': [MonthlyIncome], 'JobTenure': [JobTenure], 'NetWorth': [NetWorth], 'MonthlyLoanPayment': [MonthlyLoanPayment], 'RiskScore': [RiskScore] }) processed_data = loaded_preprocessor.transform(input_data) prediction = loaded_model.predict(processed_data)[0][0] approval_status = "Одобрено" if prediction > 0.5 else "Отказано" confidence = prediction if approval_status == "Одобрено" else 1 - prediction return approval_status, f"{confidence*100:.2f}%", float(prediction) # Создание интерфейса Gradio inputs = [ gr.Number(label="Возраст", minimum=18, maximum=100), gr.Number(label="Годовой доход", minimum=0), gr.Number(label="Credit Score", minimum=300, maximum=850), gr.Dropdown(label="Работа", choices=["Employed", "Self-Employed", "Unemployed"]), gr.Dropdown(label="Образование", choices=["High School", "Associate", "Bachelor", "Master", "Doctorate"]), gr.Number(label="Опыт работы", minimum=0, maximum=50), gr.Number(label="Размер кредита", minimum=0), gr.Number(label="Длительность выплаты", minimum=1), gr.Dropdown(label="Семейное положение", choices=["Single", "Married", "Divorced", "Widowed"]), gr.Dropdown(label="Собственность", choices=["Own", "Mortgage", "Rent", "Other"]), gr.Number(label="Выплата в месяц", minimum=0), gr.Number(label="Коэффициент использования кредитной карты", minimum=0, maximum=1), gr.Number(label="Количество открытых кредитных линий", minimum=0), gr.Radio(label="История банкротства", choices=[0, 1]), gr.Dropdown(label="Цель кредита", choices=["Home", "Debt Consolidation", "Education", "Auto", "Other"]), gr.Radio(label="Предыдущие дефолты по кредитам", choices=[0, 1]), gr.Number(label="Кол-во предыдущих платежей(месяц)", minimum=0), gr.Number(label="Длина кредитной истории (лет)", minimum=0), gr.Number(label="Баланс сберегательного счета", minimum=0), gr.Number(label="Баланс дебетовой карты", minimum=0), gr.Number(label="Всего активов", minimum=0), gr.Number(label="Всего обязательств", minimum=0), gr.Number(label="Ежемесячный доход", minimum=0), gr.Number(label="Стаж работы (лет)", minimum=0), gr.Number(label="Полная стоимость имущества", minimum=0), gr.Number(label="Ежемесячный платеж по кредиту", minimum=0), gr.Number(label="Оценка риска", minimum=0, maximum=100) ] # Создание и запуск интерфейса iface = gr.Interface( fn=predict_loan_approval, inputs=inputs, outputs=[ gr.Label(label="Ответ модели"), gr.Textbox(label="Уверенность модели"), gr.Number(label="Вероятность(от 0 до 1)") ], title="Калькулятор одобрения кредита", description='', ) iface.launch(debug=True)