CoolFace
Apppublic

amarnath2004/sathwik

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py262 linesDownload Raw Back to root
1from flask import *2import numpy as np3import pandas as pd4from sklearn.model_selection import train_test_split5from imblearn.over_sampling import SMOTE6from sklearn.metrics import accuracy_score7from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier, VotingClassifier, StackingClassifier8from sklearn.linear_model import LogisticRegression9from sklearn.tree import DecisionTreeClassifier10import mysql.connector, joblib, re11 12app = Flask(__name__)13 14mydb = mysql.connector.connect(15    host="mysql-72b75fc-klu-0662.d.aivencloud.com",16    user="avnadmin",17    password="AVNS_B_PN9K51w3EPTXtWYzR",18    port="15519",19    database='defaultdb'20)21 22mycursor = mydb.cursor()23 24def executionquery(query,values):25    mycursor.execute(query,values)26    mydb.commit()27    return28 29def retrivequery1(query,values):30    mycursor.execute(query,values)31    data = mycursor.fetchall()32    return data33 34def retrivequery2(query):35    mycursor.execute(query)36    data = mycursor.fetchall()37    return data38 39 40@app.route('/')41def index():42    return render_template('index.html')43 44@app.route('/about')45def about():46    return render_template('about.html')47 48 49@app.route('/register', methods=["GET", "POST"])50def register():51    if request.method == "POST":52        name = request.form['name']53        email = request.form['email']54        password = request.form['password']55        c_password = request.form['c_password']56        if password == c_password:57            query = "SELECT UPPER(email) FROM users"58            email_data = retrivequery2(query)59            email_data_list = []60            for i in email_data:61                email_data_list.append(i[0])62            if email.upper() not in email_data_list:63                query = "INSERT INTO users (name, email, password) VALUES (%s, %s, %s)"64                values = (name, email, password)65                executionquery(query, values)66                return render_template('login.html', message="Successfully Registered! Please go to login section")67            return render_template('register.html', message="This email ID is already exists!")68        return render_template('register.html', message="Conform password is not match!")69    return render_template('register.html')70 71 72@app.route('/login', methods=["GET", "POST"])73def login():74    if request.method == "POST":75        email = request.form['email']76        password = request.form['password']77        78        query = "SELECT UPPER(email) FROM users"79        email_data = retrivequery2(query)80        email_data_list = []81        for i in email_data:82            email_data_list.append(i[0])83 84        if email.upper() in email_data_list:85            query = "SELECT UPPER(password) FROM users WHERE email = %s"86            values = (email,)87            password__data = retrivequery1(query, values)88            if password.upper() == password__data[0][0]:89                global user_email90                user_email = email91 92                return redirect("/home")93            return render_template('login.html', message= "Invalid Password!!")94        return render_template('login.html', message= "This email ID does not exist!")95    return render_template('login.html')96 97@app.route('/home')98def home():99    return render_template('home.html')100 101 102@app.route('/view')103def view():104    global df, x_train, y_train, x_test, y_test105    df = pd.read_csv(r'Financial Distress.csv')106    # Assuming df is your DataFrame and 'financial_distress' is your target column107    df['Financial Distress'] = df['Financial Distress'].apply(lambda x: 0 if x > -0.50 else 1)108 109    ## SPlitting the data into Training and Testing110    x = df.drop('Financial Distress', axis = 1)111    y = df['Financial Distress']112    ## Balance the data113    sm = SMOTE()114    x, y = sm.fit_resample(x, y)115    ## Splitting the dataset116    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)117 118    x_train = x_train[['x2', 'x3', 'x5', 'x8', 'x9', 'x10', 'x12', 'x13', 'x14', 'x16', 'x25',119       'x36', 'x42', 'x44', 'x46', 'x47', 'x48', 'x49', 'x52', 'x53', 'x61',120       'x62', 'x63', 'x64', 'x65', 'x66', 'x67', 'x68', 'x69', 'x70', 'x71',121       'x72', 'x73', 'x74', 'x75', 'x76', 'x77', 'x78', 'x79', 'x81']]122    123    x_test = x_test[['x2', 'x3', 'x5', 'x8', 'x9', 'x10', 'x12', 'x13', 'x14', 'x16', 'x25',124       'x36', 'x42', 'x44', 'x46', 'x47', 'x48', 'x49', 'x52', 'x53', 'x61',125       'x62', 'x63', 'x64', 'x65', 'x66', 'x67', 'x68', 'x69', 'x70', 'x71',126       'x72', 'x73', 'x74', 'x75', 'x76', 'x77', 'x78', 'x79', 'x81']]127 128    dummy = df.head(100)129    dummy = dummy.to_html()130    return render_template('view.html', data=dummy)131 132 133@app.route('/model', methods=['GET', 'POST'])134def model():135    if request.method == "POST":136        model = request.form['Algorithm']137 138        if model == '1':139            gbr = GradientBoostingClassifier()140            gbr.fit(x_train, y_train)141            y_pred = gbr.predict(x_test)142            acc_gbr = accuracy_score(y_test, y_pred) * 100143            msg = f"Accuracy of Gradient Boosting Classifier = {acc_gbr}"144            return render_template('model.html', accuracy=msg)145        146        elif model == "2":147            adb = AdaBoostClassifier()148            adb.fit(x_train, y_train)149            y_pred = adb.predict(x_test)150            acc_adb = accuracy_score(y_test, y_pred) * 100151            msg = f"Accuracy of AdaBoost Classifier = {acc_adb}"152            return render_template('model.html', accuracy=msg)153        154        elif model == "3":155            rf = RandomForestClassifier()156            rf.fit(x_train, y_train)157            y_pred = rf.predict(x_test)158            acc_rf = accuracy_score(y_test, y_pred) * 100159            msg = f"Accuracy of Random Forest Classifier = {acc_rf}"160            return render_template('model.html', accuracy=msg)161        162        elif model == "4":163            # Initialize individual models164            rf = RandomForestClassifier(n_estimators=100, random_state=42)165            gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)166            lr = LogisticRegression(max_iter=1000, random_state=42)167 168            # If you want to use soft voting (probabilistic)169            VTC = VotingClassifier(estimators=[('rf', rf), ('gb', gb), ('lr', lr) ], voting='soft')  # Use 'soft' for averaging predicted probabilities170            # Train the ensemble model with soft voting171            VTC.fit(x_train, y_train)172            y_pred = VTC.predict(x_test)173            acc_gnb = accuracy_score(y_test, y_pred) * 100174            msg = f"Accuracy of Voting Classifier = {acc_gnb}"175            return render_template('model.html', accuracy=msg)176        177        elif model == "5":178            # Define base classifiers179            base_classifiers = [ ('logistic', LogisticRegression(max_iter = 10000)), ('decision_tree', DecisionTreeClassifier()), ('random_forest', RandomForestClassifier())  ]180            # Define meta-classifier181            meta_classifier = LogisticRegression(max_iter = 10000)182            # Define the stacking classifier183            stc = StackingClassifier(estimators=base_classifiers, final_estimator=meta_classifier )184            # Train the stacking classifier185            stc.fit(x_train, y_train)186            y_pred = stc.predict(x_test)187            acc_stc = accuracy_score(y_test, y_pred) * 100188            msg = f"Accuracy of Stacking Classifier = {acc_stc}"189            return render_template('model.html', accuracy=msg)        190    return render_template('model.html')191 192@app.route('/prediction', methods=['GET', 'POST'])193def prediction():194    if request.method == 'POST':195 196        f1 = float(request.form['x2'])197        f2 = float(request.form['x3'])198        f3 = float(request.form['x5'])199        f4 = float(request.form['x8'])200        f5 = float(request.form['x9'])201        f6 = float(request.form['x10'])202        f7 = float(request.form['x12'])203        f8 = float(request.form['x13'])204        f9 = float(request.form['x14'])205        f10 = float(request.form['x16'])206        f11 = float(request.form['x25'])207        f12 = float(request.form['x36'])208        f13 = float(request.form['x42'])209        f14 = float(request.form['x44'])210        f15 = float(request.form['x46'])211        f16 = float(request.form['x47'])212        f17 = float(request.form['x48'])213        f18 = float(request.form['x49'])214        f19 = float(request.form['x52'])215        f20 = float(request.form['x53'])216        f21 = float(request.form['x61'])217        f22 = float(request.form['x62'])218        f23 = float(request.form['x63'])219        f24 = float(request.form['x64'])220        f25 = float(request.form['x65'])221        f26 = float(request.form['x66'])222        f27 = float(request.form['x67'])223        f28 = float(request.form['x68'])224        f29 = float(request.form['x69'])225        f30 = float(request.form['x70'])226        f31 = float(request.form['x71'])227        f32 = float(request.form['x72'])228        f33 = float(request.form['x73'])229        f34 = float(request.form['x74'])230        f35 = float(request.form['x75'])231        f36 = float(request.form['x76'])232        f37 = float(request.form['x77'])233        f38 = float(request.form['x78'])234        f39 = float(request.form['x79'])235        f40 = float(request.form['x81'])236 237        lee = [[f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,f30,f31,f32,f33,f34,f35,f36,f37,f38,f39,f40]]238 239        # Initialize individual models240        rf = RandomForestClassifier(n_estimators=100, random_state=42)241        gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)242        lr = LogisticRegression(max_iter=1000, random_state=42)243 244        # If you want to use soft voting (probabilistic)245        VTC = VotingClassifier(estimators=[ ('rf', rf), ('gb', gb), ('lr', lr) ], voting='soft')  # Use 'soft' for averaging predicted probabilities246 247        # Train the ensemble model with soft voting248        VTC.fit(x_train, y_train)249        result = VTC.predict(lee)250        print(result)251 252        if result == 0 :253            msg = f" The Company is financially healthy "254            return render_template('prediction.html', prediction = msg)255        else :256            msg = f" The Company is financially distressed  "257            return render_template('prediction.html', prediction = msg)258    return render_template('prediction.html')259 260 261if __name__ == '__main__':262    app.run()